本文介绍了Rails 4:将属性插入到参数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3 中,可以像这样将属性插入到 params 中:

In Rails 3, it was possible to insert an attribute into params like so:

params[:post][:user_id] = current_user.id

我正在尝试在 Rails 4 中做类似的事情,但没有运气:

I'm attempting to do something similar in Rails 4, but having no luck:

post_params[:user_id] = current_user.id

. . . .


private

  def post_params
    params.require(:post).permit(:user_id)
  end

Rails 忽略了这个插入.它不会抛出任何错误,只是悄悄地失败了.

Rails is ignoring this insertion. It doesn't throw any errors, it just quietly fails.

推荐答案

找到答案 here.您可以通过合并将其插入到 params 定义中,而不是从控制器操作中插入属性.扩展我之前的例子:

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:

private

  def post_params
    params.require(:post).permit(:some_attribute).merge(user_id: current_user.id)
  end

这篇关于Rails 4:将属性插入到参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:16