Rails has_one and belongs_to migration?

Slicekick picture Slicekick · Jun 16, 2012 · Viewed 7.9k times · Source

I'm trying to establish a relationship between two models in Rails but I am having trouble figuring out what I need to do in my migration. Any help is much appreciated.

I want each business to have a type/category such as "Automotive", or "Restaurant and Bar".

Business.rb:

class Business < ActiveRecord::Base
  has_one :category, :foreign_key => "cid"
  attr_accessible :description, :email, :facebook, :foursquare, :google, :manager,
  :mobile, :name, :phone, :url, :yelp
end

Type.rb:

class Type < ActiveRecord::Base
  attr_accessible :cid, :category
  belongs_to :business
end

CreateTypes migration file:

class CreateTypes < ActiveRecord::Migration
  def change
    create_table :types do |t|
      t.integer :cid
      t.string :category
      t.references :business

      t.timestamps
    end
  add_index :types, :cid
 end
end

CreateBusinesses migration file:

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.string :name
      t.string :url
      t.string :phone
      t.string :manager
      t.string :email
      t.boolean :mobile
      t.boolean :foursquare
      t.boolean :facebook
      t.boolean :yelp
      t.boolean :google
      t.text :description
      t.integer :cid

      t.timestamps
    end
  end
end

Answer

davidrac picture davidrac · Jun 16, 2012

It would be easiest for you to keep with rails naming conventions. If I got it correctly, a business belongs to a Type/Category. let the business reference the type. add a belongs_to on the business side and a has_many on the type/category side. Roughly like this:

class Business < ActiveRecord::Base
  attr_accessible :description, :email, :facebook, :foursquare, :google, :manager, :mobile, :name, :phone, :type_id, :url, :yelp
  belongs_to :type
end

class Type < ActiveRecord::Base
  has_many :businesses
end

class CreateTypes < ActiveRecord::Migration
  def change
    create_table :types do |t|
      t.string :category

      t.timestamps
    end
  end
end

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.string :name
      t.string :url
      t.string :phone
      t.string :manager
      t.string :email
      t.boolean :mobile
      t.boolean :foursquare
      t.boolean :facebook
      t.boolean :yelp
      t.boolean :google
      t.text :description
      t.integer :type_id

      t.timestamps
    end
  end
end