Rails - 未经许可的嵌套子参数

时间:2017-04-27 23:44:09

标签: ruby-on-rails ruby accepts-nested-attributes

父母被保存但孩子没有。如果我添加landslide.sources.create,它确实在sources表中创建了一行,其中包含正确的landslide_id,但所有其他列都为空。这是文件:

landslide_controller.rb

  def new
    @landslide = Landslide.new
    @landslide.sources.build
  end

  def create
    landslide = Landslide.new(landslide_params)
    landslide.save
  end

  def landslide_params
      params.require(:landslide).permit(:start_date, :continent, :country, :location, :landslide_type, :lat, :lng, :mapped, :trigger, :spatial_area, :fatalities, :injuries, :notes, source_attributes: [ :url, :text ])
  end

sources_controller.rb

  def new
    source = Source.new
  end

  def create
    source = Source.new(source_params)

    source.save
  end

  def source_params
    params.require(:source).permit(:url, :text)
  end

_form.html.haml

= form_for :landslide, :url => {:controller => 'landslides', :action => 'create'} do |f|

  .form-inputs
    %form#landslideForm
      #Fields
   %fieldset
        %legend Source
        = f.fields_for :sources do |s|
          .form-group.row
            = s.label :url, class: 'col-sm-2 col-form-label'
            .col-sm-10
              = s.text_field :url, class: "form-control"
          .form-group.row
            = s.label :text, class: 'col-sm-2 col-form-label'
            .col-sm-10
              = s.text_field :text, class: "form-control"


      .form-actions
        = f.button :submit, class: "btn btn-lg btn-primary col-sm-offset-5", id: "submitButton"

landslide.rb和source.rb

class Source < ApplicationRecord
  belongs_to :landslide, inverse_of: :sources
end

class Landslide < ApplicationRecord
  has_many :sources, dependent: :destroy, inverse_of: :landslide
  accepts_nested_attributes_for :sources

** routes.rb **

  resources :landslides do
    resources :sources
  end

1 个答案:

答案 0 :(得分:0)

根据您的代码,预计会使用null字段创建source。由于此处landslide.sources.create,您创建的source没有任何属性值。

要成功保存source,请执行以下步骤。

  1. 在控制器的新方法上构建source def new @landslide = Landslide.new @landslide.sources.build end
  2. 表单上的用户@landslide(在new上声明) = form_for @landslide和其他事情将保持不变。

  3. landslide.sources.create删除landslide_controller.rb,因为source会在保存landslide后自动保存。

  4. 希望上述变化可以解决您的问题。