【发布时间】:2018-08-18 19:14:15
【问题描述】:
我有两个类,用户和机会,它们利用带有 has_many :through 关系的连接表来允许用户注册一对多机会(并允许一个机会让多个用户注册)。
class User < ApplicationRecord
has_many :opportunity_enrolments, :class_name => 'OpportunityEnrolment', foreign_key: "user_id"
has_many :opportunities, through: :opportunity_enrolments, foreign_key: "opportunity_id"
has_secure_password
validates :email, presence: true, uniqueness: true
end
class Opportunity < ApplicationRecord
has_many :opportunity_enrolments, :class_name => 'OpportunityEnrolment'
has_many :users, through: :opportunity_enrolments
end
class OpportunityEnrolment < ApplicationRecord
belongs_to :opportunity
belongs_to :user
end
仅当用户和机会都存在时,用户才会注册机会。因此,注册功能将在用户和机会的创建之外进行,它们分别发生并且工作正常。我认为我可以在查看 Opportunity 时使用 OpportunityEnrolment.create 方法使用以下表单和控制器向 opportunity_enrolments 表添加新行。
机会/show.html.erb
<%= form_with(model: OpportunityEnrolment.create, local: true) do |form| %>
<p>
<strong>Name:</strong>
<%= @opportunity.voppname %>
</p>
<p>
<strong>Shortdescr:</strong>
<%= @opportunity.shortdescr %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
opportunity_enrolments_controller.rb
def create
@opportunity_enrolment = OpportunityEnrolment.new(user_id: current_user.id, opportunity_id: @opportunity.id)
error checking and .save...
end
但是,我的表单中的 @opportunity.id 没有被传递给 OpportunityEnrolment.create 方法,所以我在提交时收到“nil:NilClass 的未定义方法‘id’”错误。我尝试了一种不同的方式,在表单中有一个隐藏字段(理解它不安全)并且对象仍然没有通过,但是我克服了未定义的方法错误。
我如何将对象信息 (Opportunity) 传递给另一个类 (OpportunityEnrolments),以便我可以在 opportunity_enrolments 表中添加一行?
谢谢
【问题讨论】:
标签: ruby-on-rails has-many-through