我有一个Bill对象,它有很多Due对象.该Due对象也属于Person.我想要一个可以在一个页面中创建Bill及其子项的表单Dues.我正在尝试使用嵌套属性创建表单,类似于此Railscast中的表单.
相关代码如下:
due.rb
class Due < ActiveRecord::Base
belongs_to :person
belongs_to :bill
end
Run Code Online (Sandbox Code Playgroud)
bill.rb
class Bill < ActiveRecord::Base
has_many :dues, :dependent => :destroy
accepts_nested_attributes_for :dues, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)
bills_controller.rb
# GET /bills/new
def new
@bill = Bill.new
3.times { @bill.dues.build }
end
Run Code Online (Sandbox Code Playgroud)
票据/ _form.html.erb
<%= form_for(@bill) do |f| %>
<div class="field">
<%= f.label :company %><br />
<%= f.text_field :company %>
</div>
<div class="field">
<%= f.label :month …Run Code Online (Sandbox Code Playgroud) 关于这个主题至少有10个问题,但没有一个回答这个问题.许多问题都与Rails的形式像这样,我没有,或者是更复杂的,像JSON结构,这还是这个.
编辑关于已接受的答案以及为什么这不是完全相同的
来自@CarlosRoque的答案中的链接问题最初看起来是同样的问题,但它只解决了这个特定问题的Rails方面.
如果您阅读了所有注释,您将看到多次尝试更改template_params方法,使用"template_items_attributes"对嵌套属性"template_items"进行RENAME或REPLACE.这是必要的,因为Rails accepts_nested_attributes_for需要将"_attributes"附加到名称,否则它无法看到它.
如果你检查修复wrap_parameters的答案中的猴子补丁代码,以便它适用于嵌套属性,你仍然会遇到它实际上找不到"template_items"(嵌套对象)的问题,因为它没有后缀"_attributes ".
因此,要完全解决此问题,还必须修改客户端以将嵌套对象作为"template_items_attributes"发送.对于JS客户端,可以通过在对象上实现toJSON()方法来完成,以便在序列化期间对其进行修改(此处为示例).但请注意,当您反序列化JSON时,您需要手动创建该对象的实例以使toJSON()起作用(在此解释原因).
我有一个简单的has_many/belongs_to:
楷模:
class Template < ApplicationRecord
belongs_to :account
has_many :template_items
accepts_nested_attributes_for :template_items, allow_destroy: true
end
class TemplateItem < ApplicationRecord
belongs_to :template
validates_presence_of :template
enum item_type: {item: 0, heading: 1}
end
Run Code Online (Sandbox Code Playgroud)
从客户端发送的json看起来像这样:
{
"id": "55e27eb7-1151-439d-87b7-2eba07f3e1f7",
"account_id": "a61151b8-deed-4efa-8cad-da1b143196c9",
"name": "Test",
"info": "INFO1234",
"title": "TITLE1",
"template_items": [
{
"is_completed": false,
"item_type": "item"
},
{
"is_completed": false,
"item_type": "heading"
}
]
} …Run Code Online (Sandbox Code Playgroud) 我得到一个Unpermitted parameters: latitude, longitude, address错误日志中,当我尝试接受来自表格嵌套属性。确切的参数如下所示:
{
"widget"=> {
"owner"=>"100",
"name"=>"Widget Co",
"locations_attributes" => {
"0"=> {
"latitude"=>"51.4794259",
"longitude"=>"-0.1026201",
"address"=>"123 Fake Street"
}
}
},
"commit"=>"Create Supplier",
"action"=>"create",
"controller"=>"widgets"
}
Run Code Online (Sandbox Code Playgroud)
小部件has_many位置和小部件位置belongs_to。widgets_controller我认为可以在“ 0”以下允许所有参数的参数中设置了参数,但似乎不是吗?
def widget_params
params.require(:widget).permit(:owner, :name, locations_attributes: [{"0" => []}])
end
Run Code Online (Sandbox Code Playgroud)
有没有一种可行的/更好的方式来接受这些参数?
谢谢