has_many :通过在创建时不设置所有列
我的用户和问题通过名为 voterships 的模型由 has_many 加入。用户对问题进行投票。用户可以投票赞成或反对,并且加入模型包含 user_id 和 issues_id。但是,当我去创建新投票时,只创建其中一列。我知道我做错了。这是我的文件:
class Issue < ActiveRecord::Base
has_many :associations, :dependent => :destroy
has_many :users, :through => :associations
has_many :voterships
has_many :users, :through => :voterships
belongs_to :app
def cast_vote_up!
voterships.create!(:issue_id => self.id)
end
end
这是在投票控制器中:
def create
session[:return_to] = request.referrer
#debugger
@issue = Issue.find(params[:votership][:issue_id])
@issue.cast_vote_up!
redirect_to session[:return_to]
end
投票模型:
class Votership < ActiveRecord::Base
belongs_to :user
belongs_to :issue
end
以及带有投票按钮的视图:
<%= form_for(@issue.voterships.build(:issue_id => @issue.id)) do |f| %>
<%= f.hidden_field :issue_id %>
<%= f.submit "VoteUp" %>
<% end %>
I have users and issues which are joined by a has_many through model called voterships. Users vote on issues. A user can either vote up or down and the join model contains the user_id and the issue_id. However, when I go to create a new vote, only one of the columns gets created. I know i'm doing this wrong. Here are my files:
class Issue < ActiveRecord::Base
has_many :associations, :dependent => :destroy
has_many :users, :through => :associations
has_many :voterships
has_many :users, :through => :voterships
belongs_to :app
def cast_vote_up!
voterships.create!(:issue_id => self.id)
end
end
and this is in the votership controller:
def create
session[:return_to] = request.referrer
#debugger
@issue = Issue.find(params[:votership][:issue_id])
@issue.cast_vote_up!
redirect_to session[:return_to]
end
votership model:
class Votership < ActiveRecord::Base
belongs_to :user
belongs_to :issue
end
and the view with the vote button:
<%= form_for(@issue.voterships.build(:issue_id => @issue.id)) do |f| %>
<%= f.hidden_field :issue_id %>
<%= f.submit "VoteUp" %>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要向@issue.cast_vote_up提供current_user.id!方法。
在 Votership 模型中进行某种验证是件好事,至少对于 user_id 和 issues_id 的存在而言。
You need to provide current_user.id to @issue.cast_vote_up! method.
Would be good to have some kind of validation in Votership model, at least for user_id and issue_id presence.