Rails passes an optional model parameter

in the controller I have a create action

  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

I want to pass another parameter called current_user to the model, how to do it and how to get the passed parameter in the model method?

+5
source share
2 answers
@note = Note.new(params[:note].merge(:user_id => current_user.id))

But perhaps this is not the best way how you do it, look at this: Adding a variable to parameters in rails

If you want to access current_user in the model, see Rails 3 devise, current_user is not available in the model?

+3
source

Usually you do this with a hidden field.

So, in your create view, you have to add current_user to the hidden field.

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

[: note] [: current_user] , , "current_user"

+1

All Articles