简体   繁体   English

控制器中的Rails 4设置参数?

[英]Rails 4 settings params in controller?

How can I override params in a rails 4 controller? 如何在rails 4控制器中覆盖params?

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. 即使我手动设置它,也会抛出一个Post type can't be blank错误。

Here is what my strong parameter function looks like: 这是我的强参数函数的样子:

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

The problem is with permit . 问题在于permit It's returning a new hash, so you're not actually changing the params variable (which isn't a normal variable anyway) 它返回一个新的哈希,所以你实际上并没有改变params变量(这不是一个正常的变量)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM