tl,博士:是否可以用accepts_nested_attributes
填充三元关联并因此通过this PR的测试?
基本上,我创建了四个模型A
,B
,C
和Abc
,而后者是用于与其他模型进行三元关联的联接表。问题是使用accepts_nested_attributes_for
,我似乎无法保存整个三元关联。相反,我要么创建两个具有二进制关联的联接模型(A-B,B-C或A-C),要么数据库抱怨缺少外键。结帐this test和代码:
class A < ApplicationRecord
has_and_belongs_to_many :bs, join_table: :abcs
has_and_belongs_to_many :cs, join_table: :abcs
accepts_nested_attributes_for :bs, :cs
end
class B < ApplicationRecord; end
class C < ApplicationRecord; end
class Abc < ApplicationRecord
belongs_to :a
belongs_to :b
belongs_to :c
end
class AsController < ApplicationController
def new
@a = A.new
@a.bs.build
@a.cs.build
end
def create
@a = A.new(a_params)
if @a.save
redirect_to(new_a_path)
else
render(:new)
end
end
def a_params
params.require(:a).permit(:name, bs_attributes: [:name], cs_attributes: [:name])
end
end
<%= form_for(@a) do |f| %>
<% if @a.errors.any? %>
<ul>
<% @a.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<%= f.label(:name) %>
<%= f.text_field(:name) %>
<ul>
BS:
<%= f.fields_for(:bs) do |ff| %>
<li>
<%= ff.label(:name) %>
<%= ff.text_field(:name) %>
</li>
<% end %>
</ul>
<ul>
CS:
<%= f.fields_for(:cs) do |ff| %>
<li>
<%= ff.label(:name) %>
<%= ff.text_field(:name) %>
</li>
<% end %>
</ul>
<%= f.submit %>
<% end %>
我也尝试从三元表创建它,该三元表适用于模型之间的单个关联(A-B-C),但是对于多个模型(A1-B1-C1,A1-B2-C1)则不可能。签出代码:
class AsController < ApplicationController
def new
@abc = Abc.new
@abc.build_a
@abc.build_b # 2.times { @abc.build_b } only overwrites @abc.b
@abc.build_c
end
end
无论哪种Rails只能在两个模型之间创建关联,而使三元模型缺少一个关联。
我已经将此问题作为存储库的拉取请求隔离了,如您所见HERE