Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5270

Rails pass additional parameter to a model

in a 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 to the model another param called current_user, how to do that and how to retrive the passed param in a model method?

Upvotes: 5

Views: 6711

Answers (2)

Mik
Mik

Reputation: 4187

@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 variable to params in rails

If you want access to current_user in model, see: Rails 3 devise, current_user is not accessible in a Model ?

Upvotes: 3

RadBrad
RadBrad

Reputation: 7304

Typically you do that with a hidden_field.

So in your create view, you'd add current_user as a hidden field.

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

Then in the create controller params[:note][:current_user] would be defined, and added to your model, assuming your model has an attribute called 'current_user'

Upvotes: 1

Related Questions