问题
I've been following this Rails tutorial:
http://guides.rubyonrails.org/getting_started.html
Section 5.7 tells me that I should expect an ActiveModel::ForbiddenAttributesError
The thing is, I don't get the error. It works without the permit keyword.
My create method looks like this:
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
I'm working with Rails 4.0 and Ruby 2.0. Any idea why the strong parameters security function isn't working?
回答1:
The documentation is actually misleading, you're right.
If you coded your controller as shown in chapter 5.6
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
private
def post_params
params.require(:post).permit(:title, :text)
end
you're already permitting the use of the parameters title
and text
.
The next chapter (5.7) assumes you didn't use the permit
-method already.
If you'd change Line 2 to:
@post = Post.new(post_params)
as seen in the screenshot, the error will be thrown. Additionally, the 'fix' in chapter 5.7 doesn't define a new private method post_params
as you did, but applies the fix inline.
@post = Post.new(params[:post].permit(:title, :text))
回答2:
By Any chance do you have this code in your posts_controller:
private
def post_params
params.require(:post).permit(:title, :text)
end
according to the new security measure conventions in rails 4 http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters if you have this , that means you are permitting to use those params to be used in the creation and updation of models.
and as you said you are following this tutorial http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller
you have this code in your controller.
回答3:
Doh... followed the documentation word for word -- yes, it is misleading.
The permit is already in the post_params method:
def post_params
params.require(:post).permit(:title, :text)
end
来源:https://stackoverflow.com/questions/18015604/getting-started-with-rails-tutorial-5-7-showing-posts-no-forbidden-attribute