Yaroslav February 2016

Ruby Mash using

Im using Grape and can't understand why i can't alter params Mash.

  class Publisher < ActiveRecord::Base  
  end

Following is working fine:

  post do
    Publisher.create!({
      name: params[:name],
      partner_id: @current_partner.id
    })
  end

and creates new record in my DB with name and partner_id provided

but i have many entries in params so i want to just add partner_id to them.

  post do
    p params
    params.partner_id = @current_partner.id
    p params
    Publisher.create!(params.require(:name, :partner_id))
  end

output:

#<Hashie::Mash name="myName">
#<Hashie::Mash name="myName" partner_id=1>

but it insert line in DB with NULL in partner_id column

Is it incorrect use?

Also i can't use just params in update() because of ActiveModel::ForbiddenAttributesError is it correct workaround?

Answers


bloopletech February 2016

Regarding the params in update(), this is a security feature in Rails called Strong Parameters; see https://blog.8thlight.com/will-warner/2014/04/05/strong-parameters-in-rails.html and http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters for more information.

Regarding your first problem, I think your call to require should be to permit instead:

Publisher.create!(params.permit(:name, :partner_id))

But it depends on if your request parameter names are Rails-like, i.e. publisher[name], or bare as in name. If you are doing Rails-like parameters, you will want:

Publisher.create!(params.require(:publisher).permit(:name, :partner_id))


Yaroslav February 2016

I have noticed that not only partner_id is null, but name also. So doing Publisher.create!(params.to_h) was solving my problem.

Post Status

Asked in February 2016
Viewed 3,429 times
Voted 12
Answered 2 times

Search




Leave an answer