Rails 4 Strong Parameters - Handling Missing Model Params Hash

前端 未结 2 512
轮回少年
轮回少年 2021-01-03 23:49

Models: Posts and Users

Post belongs_to :user
User has_many :posts

Simple.

Assuming a few users exist, we visit the edit page for a Post.

相关标签:
2条回答
  • 2021-01-04 00:12

    I have a similar problem, and didn't like either of these answers much. In the rails documentation (http://guides.rubyonrails.org/action_controller_overview.html#more-examples) I see the following solution:

    params.fetch(:blog, {}).permit(:title, :author)
    

    Effectively you are supplying a default of {}, which seems to work well enough (at least for my situation).

    Applying to your code, you'd have:

    params.fetch(:post, {}).permit(:user_id)
    

    I think this is reasonably clean, and seems to work in my code.

    0 讨论(0)
  • 2021-01-04 00:13

    This was my immediate solution... though it seems a bit silly because why are you having to check for the post params if you are clearly in the post controller and you require them anyways. Seems very counterintuitive. Is this really the best way?

      params.require(:post).permit(:user_id) if params[:post]
    
    0 讨论(0)
提交回复
热议问题