所以我有一个名为cities的模型和一个名为stores的模型。我想连接我的商店和城市模型,以便我可以在需要时调用商店的城市(例如@ Store.city)。我该怎么做?
我假设我需要商店模型中的has_many:cities标记和cities模型中的belongs_to:store标记。我有点迷失过去。非常感谢任何帮助?
答案 0 :(得分:2)
首先警告的是。除非有意,否则在RoR中使用复数作为模型名称是非常规的。因此,Stores
应为Store
。同样,对于城市。
我猜你想要一个城市拥有多少商店的关系。在这种情况下,您需要商店中的外键,表示商店属于一个城市。
rails generate model City
rails generate model Store
在商店模型中,您要添加
belongs_to :city
在您的城市模型中,您要添加
has_many :stores
<强>更新强>
确保您的商店表中有一个名为city_id
<强>答案强>
“我如何处理外键?”
您只需将其添加到表格中即可。 Rails会自动为您建立此连接。更确切地说。在stores
表格迁移中,请确保您有
.....
t.integer :city_id
.....
答案 1 :(得分:2)
如果每个商店只在一个城市:
首先,确保您的商店表格中包含city_id
字段。
您的商店模型将包含
belongs_to :city
并且城市模型将具有
has_many :stores
这将允许您访问城市中的所有商店:
@city = City.find_by_id(id)
@city.stores #gives an array of stores belonging to that city.
您还可以获得特定商店的城市:
@store = Store.find_by_id(id)
@store.city #gives the record for this store's city, this is based on the city_id field in your stores table
如果您的商店是连锁店,并且有可能在许多城市,那么您需要设置一些不同的东西。您需要在城市和商店之间建立另一个表,以获得“多对多”连接。该表可以称为city_stores
,其中每个记录包含一个store_id和一个city_id。
然后你的模特也改变了一点:
model Store < ActiveRecord::Base
has_many :city_stores
has_many :cities, :through => :city_stores
end
model City < ActiveRecord::Base
has_many :city_stores
has_many :stores, :through => city_stores
end
@store.cities #now gives a list of all the cities this store resides in
@city.stores #still gives a list of all stores in the city
答案 2 :(得分:0)
您应该在商店模型中查看本指南A Guide to Active Record Associations并确认:
belongs_to :city
你有一个:
在您的city_id
表格中 stores
,您将能够做到这一点,您还需要在另一方面进行关联:
:
has_many :stores
现在你将能够做类似
的事情store = Store.find(1)
store.city.name # => this will return the `name` field of the associated city
你也可以这样做:
city = City.find(1)
city.stores # => this will return an array of the stores on the selected City