2012-10-12 33 views
0

我有一个Score belongs_to Client - 和Client has_one Score如何为current_user和has_one关联分配一个新对象?

我也想在创建时指定ScoreUser。因此,每次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相同。

什么给?

回答

1

只要你有Score.belongs_to :user,以及伴随user_id列在表scores

def create 
    @score = Score.new(params[:score]) 
    @score.user = current_user 

    ... 
end 

让我知道如果你需要更多的解释,但我觉得代码是相当清楚的。

编辑或者:与其current_user.scores.new,使用current_user.scores.build(params[:score]),并确保你已经User.has_many :scores

+0

不应该'@score = current_user.scores.new(PARAMS [:评分])'这样做呢?为什么不同? – marcamillion

+0

如果不这样做,按照我的方式做这件事有什么意义 - 或者没有必要这样做? – marcamillion

+0

'current_user.scores'返回一个Array(或者'ActiveRecord :: Relation'的实例,取决于关联的设置),所以你会得到一个错误。你可以使用Rails助手''current_user.scores.build(params [:score])'这将会做你想要的,但我发现它更加清楚按照我指定的方式去做(它们基本上是同样)。 – bricker

相关问题