has_many:通过在创建时不设置所有列

时间:2011-11-23 17:59:44

标签: ruby-on-rails has-many-through

我有一些用户和问题,这些用户和问题由名为选民的has_many模型加入。用户对问题进行投票。用户可以向上或向下投票,连接模型包含user_id和issue_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 %>

1 个答案:

答案 0 :(得分:1)

您需要向@ issue.cast_vote_up提供current_user.id!方法

def cast_vote_up!(user_id)
  voterships.create!(:issue_id => self.id, :user_id => user_id)
end

在Votership模型中进行某种验证会很好,至少对于user_id和issue_id存在。