2012-06-16 161 views
2

我正在尝试在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 

回答

3

这对您来说最容易遵守rails命名约定。如果我得到了正确的答案,一个企业就属于一个类型/类别。让业务参考类型。在业务端添加belongs_to,在类型/类别端添加has_many。大致如下:

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 
+0

这是有道理的,但我如何验证它正在工作? – Slicekick

+0

我redid迁移,但我应该'attr_accessible:category'添加到我的类型模型,以便我可以创建类别,对不对? – Slicekick

+0

在定义模型并迁移数据库之后,您可以简单地运行rails c并尝试创建模型和关联:t = Type.create; b = t.businesses.create; b.type == t – davidrac

0

您的businesses表必须具有整数字段cid,因为它将其设置为外键。您的types表格不得有cid字段。 types.id字段将用于创建关系。请注意,belongs_to方法没有foreign_key选项,您应该将其从通话中删除。

我可以建议你不要无缘无故改变外键名称。如果您不指定外键,则默认为type_id

+0

我有点理解你在说什么。我将编辑我的原始文章,反映对我的文件所做的更改。尽管如此,我仍然没有100%清楚,所以我希望有进一步的阐述。 – Slicekick

+0

你有哪个错误? –

+0

我没有错误,但是如何检查该关联是否正常工作? – Slicekick