Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't mass-assign protected attributes in Rails 4

I can't understand what's wrong with my code (Rails 4):

parameters from post:

{:name => "name"}

new action:

m=Menu.new(params.permit(:name))

Last line of this code generates "Can't mass-assign protected attributes for Menu: name"

like image 665
Alexander Shlenchack Avatar asked Aug 23 '13 18:08

Alexander Shlenchack


1 Answers

The standard way to use strong_parameters in Rails 4 is to create a private method in the controller that defines the permitted params. Like so:

def new
  @m = Menu.new(menu_params)
end

private

def menu_params
  params.require(:menu).permit(:name, :etc, :etc)
end

Then, you can remove the attr_accessible line from the model.

See:

http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html http://railscasts.com/episodes/371-strong-parameters

like image 72
Chris C. Avatar answered Sep 21 '22 18:09

Chris C.