我有一个Score
belongs_to Client
- 和Client
has_one Score
。如何为current_user和has_one关联分配一个新对象?
我也想在创建时指定Score
到User
。因此,每次current_user
为特定客户创建分数时,我都希望current_user.id
与该Score
记录一起存储。
这样做的最好方法是什么?
我在想,一个优雅的方式可能是Score belongs_to User, :through Client
,但这是行不通的。
因此,我假设最好的方法是只需将user_id
添加到Score
模型中,并像这样做。
但是我该如何在Score#create
中指定user_id
?
这是怎么看我的创建操作:
def create
@score = current_user.scores.new(params[:score])
respond_to do |format|
if @score.save
format.html { redirect_to @score, notice: 'Score was successfully created.' }
format.json { render json: @score, status: :created, location: @score }
else
format.html { render action: "new" }
format.json { render json: @score.errors, status: :unprocessable_entity }
end
end
末
这自动分配电流得分的client_id
是在params[:score]
哈希 - 但它不会做user_id
相同。
什么给?
不应该'@score = current_user.scores.new(PARAMS [:评分])'这样做呢?为什么不同? – marcamillion
如果不这样做,按照我的方式做这件事有什么意义 - 或者没有必要这样做? – marcamillion
'current_user.scores'返回一个Array(或者'ActiveRecord :: Relation'的实例,取决于关联的设置),所以你会得到一个错误。你可以使用Rails助手''current_user.scores.build(params [:score])'这将会做你想要的,但我发现它更加清楚按照我指定的方式去做(它们基本上是同样)。 – bricker