Rails 4 Strong Parameters - Handling Missing Model Params Hash

前端 未结 2 521
轮回少年
轮回少年 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.

提交回复
热议问题