Rails - 通过嵌套属性在 has_many 中发布

Rails - Issue in has_many through with nested attributes

我在通过与嵌套属性的关系保存 has_many 时遇到问题。由于应用程序的复杂性和要求,关系如下

Table结构,

agreements:
  id

agreement_rooms:
  id
  agreement_id
  room_id

details:
  id
  agreement_rooms_id

为了进一步说明,agreement_rooms table 与许多其他模型相关,这些模型中将包含 agreement_rooms_id。

Rails 个协会,

class Agreement < ActiveRecord::Base
  has_many :details,:through => :agreement_rooms
  accepts_nested_attributes_for :details
end

class AgreementRoom < ActiveRecord::Base
  has_many :details
end

class Detail < ActiveRecord::Base
  belongs_to :agreement_room
  accepts_nested_attributes_for :agreement_room
end

当我尝试创建其中包含详细信息哈希的协议记录时,出现以下错误,

Agreement.last.details.create()

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'agreement#details' because the source reflection class 'Detail' is associated to 'agreementRoom' via :has_many.

我不确定如何通过上述示例的关系让这个嵌套属性与 has_many 一起使用。请帮忙解决问题。

提前致谢。

#app/models/aggreement.rb
class Agreement < ActiveRecord::Base
   has_many :agreement_rooms
   accepts_nested_attributes_for :agreement_rooms
end

#app/models/agreement_room.rb
class AgreementRoom < ActiveRecord::Base
   belongs_to :agreement
   belongs_to :room

   has_many :details
   accepts_nested_attributes_for :details
end

#app/models/room.rb
class Room < ActiveRecord::Base
   has_many :agreement_rooms
   has_many :agreements, through: :agreement_rooms
end

#app/models/detail.rb
class Detail < ActiveRecord::Base
   belongs_to :agreement_room
end

--

#app/controllers/agreements_controller.rb
class AgreementsController < ApplicationController
   def new
      @agreement = Agreement.new
      @agreement.agreement_rooms.build.details.build
   end

   def create
      @agreement = Agreement.new agreement_params
      @agreement.save
   end

   private

   def agreement_params
      params.require(:agreement).permit(:agreement, :param, agreement_rooms_attributes: [ details_attributes: [:x] ])
   end
end

#app/views/agreements/new.html.erb
<%= form_for @agreement do |f| %>
   <%= f.fields_for :agreement_rooms do |ar| %>
      <%= ar.fields_for :details do |d| %>
         <%= d.text_field :x %>
      <% end %>
   <% end %>
   <%= f.submit %>
<% end %>

您需要定义两个关联:

class Agreement < ActiveRecord::Base
  has_and_belongs_to_many :agreement_rooms # or has_many if you prefer
  has_many :details,:through => :agreement_rooms
  accepts_nested_attributes_for :details
end

检查the docs

正如我之前所说,我们的模型关联设计不合适,并且由于维护不善,它必须采用相同的方式,至少现在是这样。所以我不得不写一个脏补丁来修复它。

它只是跳过了这个特定模型的嵌套属性,因此可以通过将主记录 ID 传递给该记录来单独保存。

由于它是一个肮脏的解决方案,我没有将其标记为答案。刚刚添加它希望有人可以在需要时提供解决方案。

感谢帮助