Ruby on rails 铁轨以茧的形式嵌套。属性使用模型
我试图创建一个嵌套表单,其中包含选项和子选项,这两个选项都来自同一个名为Option的模型。以下是文件的内容: 型号:Ruby on rails 铁轨以茧的形式嵌套。属性使用模型,ruby-on-rails,nested-forms,has-many,belongs-to,cocoon-gem,Ruby On Rails,Nested Forms,Has Many,Belongs To,Cocoon Gem,我试图创建一个嵌套表单,其中包含选项和子选项,这两个选项都来自同一个名为Option的模型。以下是文件的内容: 型号: class Option < ApplicationRecord belongs_to :activity has_many :option_students has_many :students, through: :option_students has_many :suboptions, class_name: "Option",
class Option < ApplicationRecord
belongs_to :activity
has_many :option_students
has_many :students, through: :option_students
has_many :suboptions,
class_name: "Option",
foreign_key: "option_id"
belongs_to :parent,
class_name: "Option",
optional: true,
foreign_key: "option_id"
accepts_nested_attributes_for :suboptions,
reject_if: ->(attrs) { attrs['name'].blank? }
validates :name, presence: true
end
视图已正确创建,但未保存。它在创建控制器时转到“渲染:新建”。我认为这应该是参数的问题,但我不确定是什么。可能因为验证失败而没有保存。如果您使用的是rails 5,
所属的
现在更加严格,为了能够保存嵌套参数,您需要明确关联之间的连接/关系
因此,如果您将的倒数添加到您的关系中,它将如何工作,如下所示:
has_many :suboptions,
class_name: "Option",
foreign_key: "option_id",
inverse_of: :parent
belongs_to :parent,
class_name: "Option",
optional: true,
foreign_key: "option_id"
inverse_of: :suboptions
如果另一个验证失败,它还可以帮助列出表单中的错误(例如类似于@option.errors.full_messages.inspect的内容将有助于:)
顺便说一句:我会将数据库中的选项\u id
字段重命名为parent\u id
,因为这更清楚地表达了它的含义
<%= form_for @option do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<%= f.label :activity %><br>
<%= select_tag "option[activity_id]", options_for_select(activity_array) %><br>
</p>
<div>
<div id="suboptions">
<%= f.fields_for :suboptions do |suboption| %>
<%= render 'suboption_fields', f: suboption %>
<% end %>
<div class="links">
<%= link_to_add_association 'add suboption', f, :suboptions %>
</div>
</div>
</div>
<p>
<%= f.submit "Send" %>
</p>
<% end %>
<div class="nested-fields">
<%= f.label :suboption %><br>
<%= f.text_field :name %>
<%= link_to_remove_association "X", f %>
</div>
def option_params
params.require(:option).permit(:name, :activity_id, :students_ids => [], suboptions_attributes: [:id, :name])
end
has_many :suboptions,
class_name: "Option",
foreign_key: "option_id",
inverse_of: :parent
belongs_to :parent,
class_name: "Option",
optional: true,
foreign_key: "option_id"
inverse_of: :suboptions