Searching polymorphic associations in Rails
I have a need in my app to allow users to bookmark a post. They should only be able to create one bookmark per post. I've set up my polymorphic association like so:
class Post < ActiveRecord::Base
开发者_如何学运维 has_many :bookmarks, :as => :bookmarkable
end
class Bookmark < ActiveRecord::Base
belongs_to :bookmarkable, :polymorphic => true
belongs_to :user
end
class User < ActiveRecord:Base
has_many :posts
has_many :bookmarks
end
In my view, a user can create a bookmark. I would like to find some way to replace the "Create Bookmark" view code with "Delete Bookmark" code, if the user has already bookmarked a particular post.
If I try to do something like this:
@post = Post.find(params[:id, :include => [:bookmarks]])
- if @post.bookmarks.users.include?(@user)
I get a No Method error for "users"
How can I access owners of the bookmarks, to determine if the current user has already bookmarked a page?
Thank you.
I would approach this from the user's point of view:
class User < ActiveRecord::Base
has_many :posts
has_many :bookmarks
# Rails 3
def bookmarked?(post)
bookmarks.where(
{
:bookmarkable_id => post.id, :bookmarkable_type => post.class.name
}
).count > 0
end
# Rails 2
def bookmarked?(post)
bookmarks.find(:all, :conditions =>
{
:bookmarkable_id => post.id, :bookmarkable_type => post.class.name
}
).count > 0
end
end
if @user.bookmarked?(@post)
# Show delete link
else
# Show bookmark link
end
I would also advice you to add a validation to your bookmarks model that prevents a user from bookmarking the same post twice.
精彩评论