Rails 4 Strong parameters : permit all attributes?

只愿长相守 提交于 2019-11-27 05:15:59

问题


I'm building a web app with Rails 4 strong parameters.

When building the admin back office controllers, I wonder what is the best way to permit all the model attributes?

For now, I wrote this:

def user_params 
  params.require(:user).permit(User.fields.keys)
end

Do you think of a better way?


回答1:


You can call the bang version of permit.

params.require(:user).permit!

Strong Params README on Github

Source code for reference:

def permit!
  each_pair do |key, value|
    convert_hashes_to_parameters(key, value)
    self[key].permit! if self[key].respond_to? :permit!
  end

  @permitted = true
  self
end



回答2:


Skull0inc's answer works, but you might want to remove created_at and updated_at. The intention of strong params is to list only the attributes you want updatable by the controller. Something like...

def user_params
  params.require(:user).permit(User.column_names - ["created_at", "updated_at"])
end



回答3:


Would this work?

def user_params 
  params.require(:user).permit(User.column_names)
end


来源:https://stackoverflow.com/questions/14033908/rails-4-strong-parameters-permit-all-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!