R
R
Ruslan Galiev2015-11-08 21:48:20
Ruby on Rails
Ruslan Galiev, 2015-11-08 21:48:20

Rails 4 How to make changes to params?

Hello
, I have the following situation in the controller, I need to rebuild the hash of the passed parameters. Those. delete some, add new ones. In third rails, this was done in the controller without problems, for example, I could do this:

params[:user].delete('email')
params[:user][:username]='test'

But in 4 rails, strong parameters does not allow this trick to be done. Tell me if there is an option, without disabling strong parameters , to make changes in the controller code to the parameters. The option with before_action is not suitable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
O Di, 2015-11-08
@HerMajor

You can add to params, for example, in the controller using deep_merge!.
Example:

def card_params
  params.require(:card).permit(:original_text, :translated_text, :review_date, :image, :deck_id, deck: [:title]).deep_merge(deck: {user_id: current_user.id})
end

You can also create your own method in the model and use your version with delete:
def self.create_with_deck(params)
  deck_params = params.delete(:deck)
  if params[:deck_id].blank?
    deck = Deck.create(deck_params)
    params.deep_merge!(deck_id: deck[:id])
  end
  create(params)
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question