If I use :class_name attribute to has_one, what do I put in the migration?
Asked Answered
H

1

6

I have a model in my Rails app that uses the :class_name attribute for has_one:

class Foo < ActiveRecord:Base
  has_one :main_bar, :class_name => "Bar"

  # ...
end

I'm a bit unsure what to put in the migration for this class now. Can I use references? What will Rails be looking for as the column name for :main_bar? Can I do it like this?

class CreateFoos < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.references :main_bar
    end
  end

  def self.down
    drop_table :foos
  end
end

Thanks!

Hairsplitting answered 30/1, 2010 at 6:36 Comment(0)
T
7

You don't put anything in the table with the "has_one" relationship. The foreign_key goes in the other table. In your example above, you'd need to add a foreign key to your bars table.

In the migration you can use:

t.references :foo

or:

t.integer :foo_id

Either one will work.

Tincture answered 30/1, 2010 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.