rakitin
rakitin

Reputation: 2175

Reverse association for belongs_to - has_one

One thing about active record that has been confusing me (I'm still kinda new with rails). I'm doing a migration like so:

def up
    change_table :slide do |t|
        t.references => :slideable, :polymorphic => true
  end
end

and then I'll modify my models thus:

class Slide < BaseModel
  ...
  belongs_to :slideable, :polymorphic=>true
end

class Painting < BaseModel
  ...
  has_one :slide, :as => :slideable
end

class Paper < BaseModel
  ...
  has_one :slide, :as => :slideable
end

Do I also have to do a migration for the has_one relationships on Painting and Paper in order to be able to use both sides of the association?

slide.painting.name
slide.paper.title
painting.slide.name
paper.slide.name

Upvotes: 2

Views: 921

Answers (1)

Logan Serman
Logan Serman

Reputation: 29870

No, has_one does not affect your database. belongs_to is what will actually create a foreign key field in your table, that is why you need a migration.

Upvotes: 1

Related Questions