marcamillion
marcamillion

Reputation: 33755

How do I assign a new object to both current_user and a has_one association?

I have a Score that belongs_to Client - and Client has_one Score.

I also want to assign the Score to User on creation. So every time a current_user creates a score for a particular client, I want the current_user.id to be stored with that Score record.

What is the best way to do that?

I was thinking that an elegant way might be a Score belongs_to User, :through Client but that can't work.

So I am assuming the best way is to just add user_id to the Score model, and do it like that.

But then how do I assign the user_id in the Score#create?

This is how my create action looks:

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

end

This automatically assigns the current score to the client_id that is in the params[:score] hash - but it doesn't do the same for user_id.

What gives?

Upvotes: 0

Views: 95

Answers (1)

bricker
bricker

Reputation: 8941

As long as you have Score.belongs_to :user, and the accompanying user_id column in the scores table :

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

  ...
end

Let me know if you need more explanation, but I feel that the code is pretty clear.

Edit Or: Instead of current_user.scores.new, use current_user.scores.build(params[:score]), and make sure you have User.has_many :scores

Upvotes: 1

Related Questions