Rails 3加入2个belongs_to关联表

时间:2012-07-04 12:26:58

标签: mysql ruby-on-rails ruby-on-rails-3 activerecord arel

我有以下架构:

class Locale < ActiveRecord::Base
  has_many :shops

  # region : String
end

class Shop < ActiveRecord::Base
  belongs_to :locale
  has_many :carts

  scope :europe, joins(:locale).where('locales.region = ?', 'Europe')
end

class Cart < ActiveRecord::Base
  belongs_to :shop

  scope :purchased, where('purchased_at is not null')

  # purchased_at : DateTime
end

我想找到在某个地区购买的所有购物车 我有几个范围设置,以使查询更具可读性,但当我尝试:

Cart.purchased.join(:店铺).merge(Shop.europe)

我收到错误: ActiveRecord :: ConfigurationError:找不到名为“locale”的关联;也许你拼错了?

关于如何使这项工作的任何想法?

1 个答案:

答案 0 :(得分:0)

class Locale < ActiveRecord::Base
  has_many :shops

  scope :europe, where(region: 'Europe')
end

class Shop < ActiveRecord::Base
  belongs_to :locale
  has_many :carts
end


class Cart < ActiveRecord::Base
  belongs_to :shop

  scope :purchased, where('purchased_at is not null')
end

Cart.purchased.joins(shop: :locale).merge(Locale.europe)