Rails - Unpermitted nested children parameters [duplicate]

半腔热情 提交于 2019-12-25 18:24:44

问题


The parent is saved but the children isn't. If I add landslide.sources.create, it does create a row in sources table with the correct landslide_id but all the other columns are null. Here's the files:

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 and 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:


According to your code it is expected to create source with null field. Because of landslide.sources.create here you are creating source with out any attribute values.

To successfully save source follow the following step.

  1. build source on controller's new method def new @landslide = Landslide.new @landslide.sources.build end
  2. User @landslide (declared on new) on the form = form_for @landslide and other thing will remain same.

  3. remove landslide.sources.create from your landslide_controller.rb because source will save automatically after saving landslide.

Hope above changes will solve your problem.



来源:https://stackoverflow.com/questions/43669655/rails-unpermitted-nested-children-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!