简体   繁体   English

提交表单时,Rails 4参数不嵌套

[英]Rails 4 Params Not Nesting When Form Submitted

I am using Rails 4 and nested forms. 我正在使用Rails 4和嵌套表单。 I want to associate the models so the model named Lead is the parent and associated with the model named QuoteMetal. 我想关联模型,因此名为Lead的模型是父模型,并与名为QuoteMetal的模型关联。 I want someone to submit the forms and have rails write the information from the forms into tables of the database. 我希望有人提交表单并让Rails将表单中的信息写到数据库表中。 Here are my models: 这是我的模型:

class Lead < ActiveRecord::Base
    has_many :quote_metals
    accepts_nested_attributes_for :quote_metals
end
class QuoteMetal < ActiveRecord::Base
  belongs_to :lead
end

Here is the form: 形式如下:

  <%= form_for @lead, class: 'form-horizontal' do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name, class: "form-control" %>

      <%= f.label :notes %>
      <%= f.text_area :note, class: "form-control" %>

    <%= fields_for @quote_metal do |ff| %>       
            <%= ff.label :weight %><br>
            <%= ff.number_field :weight, class: "form-control" %>
                 ....
    <% end %>

    <%= f.submit "Submit" %>

  <% end %>

And my controller: 而我的控制器:

class LeadsController < ApplicationController

  def index
    @lead = Lead.new
    @quote_metal = @lead.quote_metal.build
  end

  def create
    raise params.inspect
  end

  def show
  end

private

    def lead_params
        params.require(:lead).permit([:name, ..., 
            quote_metal: [:weight....])
    end

end

The output params I get is not nested. 我得到的输出参数不是嵌套的。 It looks like: 看起来像:

{"utf8"=>"✓",
 "authenticity_token"=>"JYO/Yt/QBlytHsQaRe9+stzZvZn6xCI7ukeypMZZjpgnowktFcllLhhb2qXK/+45V5l+qJFg/5b4/yZdWLPvGg==",
 "lead"=>{"name"=>"Dick",...,"note"=>"asdf"},
 "quote_metal"=>{"weight"=>"65.20",....},
 "commit"=>"Submit"}

How do I get the params to be nested and then write those nested params to a the tables that correspond to the models - one table for the lead and one table for the metal. 如何获取要嵌套的参数,然后将这些嵌套的参数写入与模型相对应的表中-一个表用于引线,另一个表用于金属。

Change 更改

    <%= fields_for @quote_metal do |ff| %>

To

    <%= f.fields_for @quote_metal do |ff| %>

Prefixing fields_for with the form builder for the parent will scope this properly for you. 在父表单构建器之前为fields_for加上前缀fields_for您适当地确定范围。

Separately, you might also consider refactoring your quote_metal nested view into a partial. 另外,您还可以考虑将quote_metal嵌套视图重构为局部视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM