JP Silvashy
JP Silvashy

Reputation: 48525

Rails, saving the foreign key in a `belongs_to` association

I think I'm having a really basic problem here but I can't seem to put my finger on what I'm doing wrong.

So the issue here is when I save an instance of a model the foreign_key for the models's belongs_to association (in this case the user_id is not being saved, so I'm forced to do this:

def new
  @thing = Thing.new(:user_id => current_user.id)
end

def create
  @thing = Thing.new(params[:thing])
  @thing.user_id = current_user.id

  if @thing.save
    redirect_to @thing
  else
    render 'new'
  end
end

Shouldn't the user_id get saved automatically if my model has this association?

class Thing < ActiveRecord::Base
  belongs_to :user
end

The reason I'm having this issue in the first place is because the gem friendly_id has changed the way all of my ids work and now return the objects slug... pretty annoying in my opinion.

Upvotes: 2

Views: 1930

Answers (1)

Budgie
Budgie

Reputation: 2279

I would try @thing.user = User.find(current_user.id) instead in your controller. Have you also got the has_many :things association declared in your user model?

Upvotes: 4

Related Questions