Ruby-on-rails Rails 4:将属性插入到参数中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16530532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4: Insert Attribute Into Params
提问by nullnullnull
In Rails 3, it was possible to insert an attribute into params like so:
在 Rails 3 中,可以像这样在 params 中插入一个属性:
params[:post][:user_id] = current_user.id
I'm attempting to do something similar in Rails 4, but having no luck:
我试图在 Rails 4 中做类似的事情,但没有运气:
post_params[:user_id] = current_user.id
. . . .
private
def post_params
params.require(:post).permit(:user_id)
end
Rails is ignoring this insertion. It doesn't throw any errors, it just quietly fails.
Rails 忽略了这个插入。它不会抛出任何错误,它只是悄悄地失败了。
回答by nullnullnull
Found the answer here. Rather than inserting the attribute from within the controller action, you can insert it into the params definition with a merge. To expand upon my previous example:
在这里找到了答案。您可以通过合并将其插入到 params 定义中,而不是从控制器操作中插入属性。扩展我之前的例子:
private
def post_params
params.require(:post).permit(:some_attribute).merge(user_id: current_user.id)
end
回答by Fellow Stranger
In addition to @timothycommoner's answer, you can alternatively perform the merge on a per-action basis:
除了@timothycommoner 的回答之外,您还可以在每个操作的基础上执行合并:
def create
@post = Post.new(post_params.merge(user_id: current_user.id))
# save the object etc
end
private
def post_params
params.require(:post).permit(:some_attribute)
end
回答by BitOfUniverse
As an alternative for this case, you can required pass attribute via scope:
作为这种情况的替代方案,您可以通过scope以下方式要求传递属性:
current_user.posts.create(post_params)
current_user.posts.create(post_params)
回答by Hollie B.
If anyone is trying to figure out how to add/edit a nested attribute in a Rails 5 attributes hash, I found this to be the most straight-forward (alternate) approach. Don't bother with merge or deep_merge...it's a pain due to the strong parameters. In this example, I needed to copy the group_id and vendor_id to the associated invoice (nested parameters) prior to saving.
如果有人想弄清楚如何在 Rails 5 属性散列中添加/编辑嵌套属性,我发现这是最直接(替代)的方法。不要理会merge 或deep_merge ......由于强大的参数,这很痛苦。在这个例子中,我需要在保存之前将 group_id 和 vendor_id 复制到关联的发票(嵌套参数)。
def create
my_params = order_params
@order = Order.new
@order.attributes = my_params
@order.invoice.group_id = my_params[:group_id]
@order.invoice.vendor_id = my_params[:vendor_id]
@order.save
end
private
# Permit like normal
def order_params
params.require(:order).permit([:vendor_id, :group_id, :amount, :shipping,:invoice_attributes => [:invoice_number, :invoice_date, :due_date, :vendor_id, :group_id]])
end

