Rails将附加参数传递给模型

时间:2012-05-02 17:30:25

标签: ruby-on-rails ruby activerecord model

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

  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的param传递给模型,如何在模型方法中检索传递的param?

2 个答案:

答案 0 :(得分:3)

@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 ?

答案 1 :(得分:1)

通常,您使用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”的属性