【问题标题】:Rails 3 joining 2 belongs_to associated tablesRails 3加入2个belongs_to关联表
【发布时间】:2012-07-04 12:26:58
【问题描述】:

我有以下架构:

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(:shop).merge(Shop.europe)

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

对如何完成这项工作有任何想法吗?

【问题讨论】:

  • 你where中的表名是'locales',但是类是'locale',还是加了s的红宝石魔法?

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


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多