我有当前的模特关系:
class Group < ActiveRecord::Base
has_many :group_memberships, dependent: :destroy
has_many :subjects, through: :group_memberships
has_many :entries, through: :group_memberships
accepts_nested_attributes_for :group_memberships, allow_destroy: true
class GroupMembership < ActiveRecord::Base
belongs_to :group
belongs_to :subject
belongs_to :entry
class Issue < ActiveRecord::Base
has_many :group_memberships, through: :entries, dependent: :destroy
has_many :groups, through: :group_memberships, dependent: :destroy
accepts_nested_attributes_for :group_memberships, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :groups, allow_destroy: true
使用cocoon嵌套字段和simpleform - 当我添加或更新现有对象时 - 创建了两个不完整的group_membership记录(即它们将所需的外键分成两个模型。
这和我通常使用的关联之间的唯一区别是,在这种情况下,连接表有三个外键而不是两个。
SQL查询:
INSERT INTO `groups` (`name`, `created_at`, `updated_at`) VALUES ('test group', '2016-01-11 15:53:22', '2016-01-11 15:53:22')
INSERT INTO `group_memberships` (`subject_id`, `group_id`, `created_at`, `updated_at`) VALUES (16, 18, '2016-01-11 15:53:22', '2016-01-11 15:53:22')
INSERT INTO `group_memberships` (`entry_id`, `group_id`, `created_at`, `updated_at`) VALUES (20, 18, '2016-01-11 15:53:22', '2016-01-11 15:53:22')
控制器中的参数似乎正常:
"groups_attributes"=>{"1452527593321"=>{"name"=>"test group", "subject_ids"=>["", "16"], "_destroy"=>"false"}}, "_destroy"=>"false", "id"=>"20"}
当参数显示正常时,我真的有点迷失为什么我要处理重复的不完整查询
表单本身如下所示:
<div id="groups">
<div id="groups_from_list">
<%= f.simple_fields_for :groups do |group| %>
<%= render 'group_fields', :f => group %>
<% end %>
</div>
<%= link_to_add_association 'add a group', f, :groups, :class => 'btn btn-primary btn' %>
</div>
通过使用嵌套表单的关联,标准has_many没有任何问题 - 但我认为在group_membership连接表中有三个外键导致了问题。
**Group Fields Partial**
<div class="nested-fields">
<%= f.input :name , input_html: { class: 'form-control-small' }, label: "Group name" %>
<%= f.association :subjects,
include_blank: false,
label_method: :full_name,
label: "Attendees",
collection: Subject.order(:last_name),
input_html: { class: 'select2-issue-X' },
placeholder: "add attendees" %>
<%= link_to_remove_association "remove", f, :class => 'btn btn-danger btn-xs'%>
</div>
答案 0 :(得分:0)
我通过使用不同的模型关系来解决这个问题 - 我在原始帖子中使用的那个似乎不受标准嵌套字段实现的支持 - 尽管它可以通过重写控制器和模型代码来解决。
class Group < ActiveRecord::Base
has_many :group_memberships, dependent: :destroy
has_many :subjects, through: :group_memberships
class GroupMembership < ActiveRecord::Base
belongs_to :group
belongs_to :subject
class Issue < ActiveRecord::Base
has_many :groups, through: :entries
has_many :group_memberships, through: :groups, dependent: :destroy
accepts_nested_attributes_for :groups, allow_destroy: true