【问题标题】:has_many and has_many relationhas_many 和 has_many 关系
【发布时间】:2014-03-04 02:15:58
【问题描述】:

我有国家、城市、商店模型

class Country < ActiveRecord::Base
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :country
  has_many :shops 
end

class Shop < ActiveRecord::Base
  belongs_to :city
end

如何在 activerecord 中获取 country.shops? (获取国家/地区的所有商店)

我通常使用 Country.cities.collect { |c| c.商店} 但这不是 activerecord 对象。

我考虑过在 shop 模型上添加 country_id 并设置 has_many 关系,但我认为这不是最好的方法。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    在 Country 中,添加一个 has_many :through 关系:

    class Country < ActiveRecord::Base
      has_many :cities
      has_many :shops, through: :cities
    end
    

    现在您可以编写 country.shops 并接收适当的 ActiveRecord 关系,您可以在其中说出诸如 country.shops.where name:"Nieman Marcus" 之类的内容以及其他此类查询。

    【讨论】:

      【解决方案2】:

      你可以在 Class Country 中定义一个方法

      def all_shops
        self.cities.collect { |c| c.shops }
      end
      

      你也可以使用 Mongoid::Tree

      def all_shops
        Shop.where(:parent_ids => self.id)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多