Reputation: 892
I need to pass current_user
for user_id
when creating entity
. Its not working the way i'm doing it.
def create
@entity = Entity.new(entity_params, :user_id = current_user)
...
end
In Schema I have :user_id
as integer for Entity
table. I also have belongs_to :user
association in models/entity.rb
Upvotes: 1
Views: 585
Reputation: 1601
You can also try:
def create
@entity = current_user.entities.create(entity_params)
end
Upvotes: 1
Reputation: 76784
A better way:
#app/controllers/entities_controller.rb
class EntitiesController < ApplicationController
def create
@entity = current_user.entities.new entity_params
@entity.save
end
end
Upvotes: 2
Reputation: 9226
new
accepts a parameters hash, so it should work with:
@entity = Entity.new(entity_params.merge(user: current_user))
Another way would be
@entity = Entity.new(entity_params).tap do |entity|
entity.user = current_user
end
Upvotes: 3