Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
Matteo Pagliazzi Avatar asked Oct 08 '22 23:10

Matteo Pagliazzi


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

like image 122
Mik Avatar answered Oct 12 '22 12:10

Mik


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'

like image 36
RadBrad Avatar answered Oct 12 '22 11:10

RadBrad