Nested attributes - Unpermitted parameters Rails 4

2020-04-27 11:02发布

问题:

There is a lot of resources on SO about issues on Nested attributes in Rails 4 regarding strong parameters but I don't find any solution on this: (so sorry if it's a duplicate)

I have a 1-1 relation between member and profile. When trying to update a member with profile attributes I've got this error:

Unpermitted parameters: profile

Where are my params

===> params: {"member"=>{"profile"=>{"first_name"=>"test", "last_name"=>"test"}, "email"=>"test@test.com"}}

My models:

Member.rb

class Member < ActiveRecord::Base
  ...
  has_one :profile
  accepts_nested_attributes_for :profile
end

Profile.rb

class Profile < ActiveRecord::Base
  belongs_to :member
end

My form:

edit.html.slim

= simple_form_for [:admin, @member] do |f|
  = f.simple_fields_for @member.profile do |pf|
    = pf.input :first_name
    = pf.input :last_name
  = f.input :email
  = f.button :submit

and my controller:

admin/members_controller.rb

class Admin::MembersController < Admin::BaseController
  before_action :set_member, only: [:edit]

  def edit
  end

  def update
    if @member.update(member_params)
      Rails.logger.debug "===> (1)"
      redirect_to edit_admin_member_path
    else
      render action: 'edit'
    end
  end

  private
    def set_member
      @member = Member.find(params[:id])
    end

    def member_params
      params[:member].permit(:email, profile_attributes: [:first_name, :last_name ])
    end
end

I've tried many things but don't understand where is my mistake.. Moreover in the update method it says the @member is correctly updated (shown ===> (1))

回答1:

Ok get it..

I think this is caused by simple_form:

= simple_form_for [:admin, @member] do |f|
  = f.simple_fields_for :profile, @member.profile do |pf|
    = pf.input :first_name
    = pf.input :last_name
  = f.input :email
  = f.button :submit


回答2:

Try Adding the :member_id inside profile_attributes which is in member_params

so it will look like this:

def member_params
      params[:member].permit(:email, profile_attributes: [:first_name, :last_name, :member_id ])
end