我想创建一个类似于reddit的模型,用户可以在其中向上投票或否决一个链接或文章。我很难理解这个问题:我如何制作我的模型,使用户只喜欢向上或向下的链接一次,并能够改变他们的地雷(切换到否决),但永远不能投票多次,无论多少时间已经过去/注销并不重要。
发布于 2014-07-22 08:58:39
has_many :通过
你会创造出这样的东西:
#app/models/post.rb
Class Post < ActiveRecord::Base
has_many :votes do
def user(user)
find_by user_id: user.id
end
end
has_many :voters, through: votes, class_name: "User", foreign_key: "user_id"
end
#app/models/vote.rb
Class Vote < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :votes
has_many :posts, through: :votes
end标准has_many :through关系--使您能够使用join model将两个或多个其他模型关联在一起:

--
用户
这将允许您调用以下内容:
#app/views/posts/show.html.erb
<% if @post.votes.user(current_user).present? %>
<% link_path = @votes.votes.user(current_user).value == "up" ? vote_down_path : vote_up_path %>
<%= link_to "Vote", link_path %>
<% else %>
# empty vote link
<% end %>棘手的一点是将一次投票与单个用户关联起来--因此,我为您的ActiveRecord关联扩展关联添加了一个votes。
发布于 2014-07-22 08:53:32
你可以利用人际关系来捕捉这个..。
https://stackoverflow.com/questions/24882679
复制相似问题