【问题标题】:Rails pass additional parameter to a modelRails 将附加参数传递给模型
【发布时间】:2012-05-02 17:30:24
【问题描述】:

在控制器中我有一个创建操作

  def create

    params[:note]
    @note = current_user.notes.new(params[:note])

      if @note.save
        respond_with @note, status: :created
      else
        respond_with @note.errors, status: :unprocessable_entity
      end
  end

我想将另一个名为 current_user 的参数传递给模型,如何做到这一点以及如何在模型方法中检索传递的参数?

【问题讨论】:

  • 您想将该参数传递给哪个模型?

标签: ruby-on-rails ruby activerecord model


【解决方案1】:
@note = Note.new(params[:note].merge(:user_id => current_user.id))

但也许这不是最好的方法,看看这个:Adding variable to params in rails

如果您想访问模型中的 current_user,请参阅:Rails 3 devise, current_user is not accessible in a Model ?

【讨论】:

  • 你不需要merge,当你可以直接赋值时:params[:note][:user_id] = current_user.id 请记住merge返回一个副本,所以这不会改变参数,而是返回一个版本其他条目。
  • 感谢您的澄清。当我写回复时,我的意思是在调用new时使用merge。即:Note.new(params[:note].merge(:user_id => current_user.id)) 对吗?
  • 这是有道理的,因为您使用了结果。 merge 在 void 上下文中几乎总是毫无意义的。
【解决方案2】:

通常您使用 hidden_​​field 来执行此操作。

因此,在您的创建视图中,您需要将 current_user 添加为隐藏字段。

<%= form_for @note do |f| %>
  # all your real fields
  <%= f.hidden_field :current_user current_user %>
<% end %>

然后在创建控制器中定义 params[:note][:current_user] 并将其添加到您的模型中,假设您的模型有一个名为 'current_user' 的属性

【讨论】:

  • 虽然添加自定义隐藏字段可能会有所帮助,但我不会为 current_user。恶意用户在提交之前更改表单内容太容易了。现在,您的表中有一条记录表明 Bob 做了某事,而实际上是 Alice...按照 Mikhail 的建议将其移至控制器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 2013-01-09
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多