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?
@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 ?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With