A
A
Alex Goncharov2014-02-22 23:50:31
Ruby on Rails
Alex Goncharov, 2014-02-22 23:50:31

How does params work in Rails 4?

What to do if there can be many fields passed to the controller?
Rails 3.2:

def create
  @item = Item.create(params[:item])
end

Rails 4.0
def create
  @item = Item.create(items_params)
end
#Как работает данная конструкция?
private
  def items_params 
   params.require(:item).permit(:name, :price, :description, :real, :weight) 
  end
end

I tried to move in by myself, but I can't do without sensei.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arkady Butermanov, 2014-02-23
@calirails

What does a lot mean?
This design is designed to transfer control over the parameters available for mass editing from the model to the controller. Because that's where he belongs.
It works as follows. params is not really a regular hash, but an object of a certain class. When the model receives such an object as parameters, it asks it for a list of attributes that can be edited.
For example:

params = { user: { email: '[email protected]', password: '123' } }

if you want to be able to edit only the email that lies inside the hash with the user, then write: params.require(:user).permit(:email).
In the event that you accept an array as a parameter:params.permit(:some_hash).require(some_array: [])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question