First I want to thank the community for their help and here is my
question
I have a simple add to fdavourites functionality. A user can add a post
to their favouirites. Thing is I want to display the “add to favourites”
button if the post is not in the user’s favs and something else if it
is, so I need to check for this in the view.
favourites table has post_id and user_id
I tried something like
<% if current_user.favourites.exists? @post, :post_id %>
already faved
<% else %>
blabla not faved :)
<% end %>
I’m pretty sure the error is in the “@post, :post_id” part of my code
but I couldn’t find anything about the .exists? syntax in google.
Played with the code for hours and just got it to work, 20 minutes after
posting here. ruby-forum.com brought me luck, thank you
Here the working code:
<% if current_user.favourites.exists? :post_id => @post.id %>
So it checks the favs of the current_user in the fawvourites table and
compares the post_id ( which is the id of the already faved post) to the
current post that is displayed on the page.
If anyone else is wondering if that is slower or faster then
current_user.favorites.where(:post_id => @post.id).count == 1 the SQL
from the .exists? method is:
SELECT 1 FROM “favorites” WHERE “favorites”.“post_id” = 666 AND
“favorites”.user_id = 1 LIMIT 1
If anyone else is wondering if that is slower or faster then
current_user.favorites.where(:post_id => @post.id).count == 1 the SQL
from the .exists? method is:
if there is genuinely one such favourite then i don’t think it makes
much different. If there were hundreds (or thousands) then the count
method needs to find them all before it can return its result whereas
the sql from .exists? only needs to find one such row
Fred
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.