我正在尝试在Rails中建立两个模型之间的关系,但我无法弄清楚我需要在迁移中做什么。任何帮助深表感谢。Rails has_one和belongs_to迁移?
我希望每个企业都有类型/类别,例如“汽车”或“餐厅和酒吧”。
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迁移文件:
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迁移文件:
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
这是有道理的,但我如何验证它正在工作? – Slicekick
我redid迁移,但我应该'attr_accessible:category'添加到我的类型模型,以便我可以创建类别,对不对? – Slicekick
在定义模型并迁移数据库之后,您可以简单地运行rails c并尝试创建模型和关联:t = Type.create; b = t.businesses.create; b.type == t – davidrac