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

发布于 2024-12-17 11:13:12 字数 1042 浏览 3 评论 0原文

我的用户和问题通过名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼眸 2024-12-24 11:13:12

您需要向@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 和 issues_id 的存在而言。

You need to provide current_user.id to @issue.cast_vote_up! method.

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

Would be good to have some kind of validation in Votership model, at least for user_id and issue_id presence.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文