基于belongs_to的Rails Active Record搜索

时间:2015-08-10 05:02:49

标签: ruby-on-rails activerecord

我有一个国家,其中有很多区域,其中有很多商店

  

国家>区域>商店。

我想根据国家而不是地区返回所有商店的清单。像这样:

@shops = Shops.find(some query based on country = America).

谢谢,

2 个答案:

答案 0 :(得分:2)

参考Rails'关于连接表的文档。具体来说,请查看标有" 12.2.4加入嵌套关联(多级)"的小节":

http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations

您的查询可能最终会看起来像这样(尽管您可能需要检查某些符号的复数形式):

@shops = Shop.joins(:area => :countries).where(:countries => {:name => 'America'})

答案 1 :(得分:2)

您的商店属于地区,地区属于哪个国家/地区?如果是这样,也许你可以做这样的事情。

class Country
  has_many :areas
  has_many :shops, through: :areas
end

class Area
  belongs_to :country
end

class Shop
  belongs_to :area
end

所以你可以使用这样的东西:@country.shops

相关问题