Search code examples
ruby-on-rails-3associationshas-manybelongs-to

Rails Association (belongs_to) dilemma


I have a User model:

class User < ActiveRecord::Base

  has_many :cards

end

and a Card model:

   class Card< ActiveRecord::Base

      belongs_to :user, :foreign_key => "owner_id"

   end

the card model also has an attribute called "owner_id", which I'd like to use in way like this: Card.first.owner which will retrieve the User which owns that card

my problem as that, I know that rails will automagically connect the id's in the association but that doesnt happen.

in the CardController, rails get stuck in the create action on the line

@card=current_user.cards.new(params[:card])

and says unknown attribute: user_id

I've done db:migrate and it still won't work.

must I do as follows for it to work?

@card = Card.new(params[:card])
@card.owner_id=current_user.id

or am I missing something?


Solution

  • First of all, you don't need a owner_id column for this. All you need is

    class User
      has_many :cards
    end
    

    This will give you @user.cards

    class Card
      belongs_to :owner, :class_name => "User", :foreign_key => "user_id"
    end
    

    This will give you @card.owner