[英]How to pass current_user when creating new record?
I need to pass current_user
for user_id
when creating entity
. 创建
entity
时,我需要为user_id
传递current_user
。 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. 在模式中,我
:user_id
为Entity
表的整数。 I also have belongs_to :user
association in models/entity.rb
我在
models/entity.rb
也有belongs_to :user
关联
new
accepts a parameters hash, so it should work with: new
接受参数哈希,因此应使用:
@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
A better way: 更好的方法:
#app/controllers/entities_controller.rb
class EntitiesController < ApplicationController
def create
@entity = current_user.entities.new entity_params
@entity.save
end
end
You can also try: 您也可以尝试:
def create
@entity = current_user.entities.create(entity_params)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.