Hopstream
Hopstream

Reputation: 6451

Rails 4 settings params in controller?

How can I override params in a rails 4 controller?

The following doesn't seem to work:

params[:post_type_id] = 2
@post = current_user.posts.new(post_params)

This throws a Post type can't be blank error even though I'm setting it manually.

Here is what my strong parameter function looks like:

def post_params
    params.require(:post).permit(:title, :body, :post_type_id)
end

Upvotes: 0

Views: 69

Answers (1)

Niall Paterson
Niall Paterson

Reputation: 3580

The problem is with permit. It's returning a new hash, so you're not actually changing the params variable (which isn't a normal variable anyway)

This can easily be fixed by just going:

post_details = post_params
post_details[:post_type_id] = 2
@post = current_user.posts.new(post_details)

Upvotes: 2

Related Questions