该网站是一个简单的社区,每个用户创建帖子,用户可能“喜欢”他们或“不像”他们。
我有一个Post和一个Like模型。 目前,我正在通过post.likes.size列出所有帖子以及每个帖子的喜欢尺寸。 喜欢帖子的按钮也在工作。
我不知道该怎么做是如何根据情况,如果一个职位应该显示不同按钮或类似的(取决于如果current_user已经喜欢该职位)。
类似的模型非常简单:
User_id // current user Post_id // post to associate提前致谢!
The site is a simple community where each user creates posts and users may "like" them or "unlike" them.
I have a Post and a Like model. Currently, I'm listing all posts and also the likes size for each post through post.likes.size . The button to like a post is also working.
What i don't know how to do is how to depending on the case, if a post should show the unlike button or the like (depending if the current_user already liked that post).
The like model is very simple:
User_id // current user Post_id // post to associateThanks in advance!
最满意答案
您应该在用户模型中定义关联
如果它是ror 2. *在用户模型中添加方法。 它应该是这样的:
has_many :likes def already_likes?(post) self.likes.find(:all, :conditions => ['post_id = ?', post.id]).size > 0 end假设Like有字段user_id和post_id,当然还有视图
if current_user.already_likes?(@post) #add unlike button endYou should define association in user model
if it's ror 2.* add method in User model. it should look like this:
has_many :likes def already_likes?(post) self.likes.find(:all, :conditions => ['post_id = ?', post.id]).size > 0 endAssuming Like has fields user_id and post_id and of course in view
if current_user.already_likes?(@post) #add unlike button end更多推荐
发布评论