2012-10-12 2 views
0

여기에는 이 속하고 Client - Client has_one Score입니다.current_user 및 has_one 연관에 새 객체를 어떻게 할당합니까?

또한 ScoreUser을 할당하려고합니다. 따라서 current_user이 특정 클라이언트에 대한 점수를 만들 때마다 current_user.id이 해당 Score 레코드와 함께 저장되기를 바랍니다.

가장 좋은 방법은 무엇입니까?

우아한 방법이 Score belongs_to User, :through Client 일 수 있다고 생각했지만 작동하지 않습니다.

그래서 가장 좋은 방법은 Score 모델에 user_id을 추가하는 것입니다.

그런데 Score#createuser_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 

이 자동으로 params[:score] 해시에있는 client_id 현재 점수를 할당합니다 -하지만 user_id에 대한 동일한 작업을 수행하지 않습니다 .

무엇을 제공합니까?

답변

1

은 오래 당신은 Score.belongs_to :user을 가지고, 그리고 scores 테이블의 동반 user_id 열 :

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의 인스턴스 (또는 Association이 설정되는 방법에 따라'ActiveRecord :: Relation')를 반환하므로 오류가 발생합니다. 찾고자하는 것을 할 수있는 레일스 도우미'current_user.scores.build (params [: score]) '를 사용할 수는 있지만, 내가 지정한 방식대로하는 것이 더 명확하다. (기본적으로 같은). – bricker

관련 문제