我有两个模型来建立他们之间的关系,在那里我需要进入一个雷达的商店和一个商店的雷达。雷达可以监视零个或多个商店。一个商店可能属于零,一个或多个雷达。
我想要这样的东西:
store = Store.first
store.radars #all radars of the store location反之亦然:
radar = Radar.first
radar.stores #all stores of the radar location我的课:
class Store < ActiveRecord::Base
attr_accessible :title, :description, :user, :store_group, :city,
:neighborhood, :sublocality, :post_code, :route,
:street_number, :latitude, :longitude
end
class Radar < ActiveRecord::Base
attr_accessible :name, :radius, :latitude, :longitude, :user
end我如何创建一个迁移来处理这个问题?
发布于 2013-12-30 15:49:59
你要找的是雷达和商店之间的has_and_belongs_to_many关联。你需要问自己的问题是,这两种模式之间的结合会不会有什么特点呢?如果是这样的话,您可能会考虑使用显式联接模型,这将保留这些属性。在这种情况下,您将看到一个has_many :through关联。
有关HABTM协会的信息,请参见basics.html#the-has-and-belongs-to-many-association。
您对HABTM的迁移将是这样的。
class CreateRadarStores < ActiveRecord::Migration
create_table :radars_stores, :id => false do |t|
t.belongs_to :radar
t.belongs_to :store
end
end表名的顺序很重要,因为默认情况下,rails按模型的字母顺序创建它。
您的模型需要更新以包括HABTM。
class Store < ActiveRecord::Base
has_and_belongs_to_many :radars
....
end
class Radar < ActiveRecord::Base
has_and_belongs_to_many :stores
....
end或者如果使用一个有很多:通过查看这里basics.html#the-has-many-through-association
构建该连接模型将取决于您所使用的属性。
https://stackoverflow.com/questions/20842576
复制相似问题