【问题标题】:Rails - Query One Model from within a Different Model with a has_many & belongs_to relationshipRails - 从具有 has_many 和 belongs_to 关系的不同模型中查询一个模型
【发布时间】:2013-03-01 13:55:06
【问题描述】:

我并不完全清楚如何从 Rails 中的不同模型中查询模型数据。这些模型具有 has_many 和 belongs_to 关系。 2 个模型是“Gear”和“line_item”。 Gear has_many line_items 和 LineItem 属于_to Gear。

我要做的是查询数据库中属于 Gear 对象的所有 line_items,这些对象具有 NULL 或空白 cart_id(这是字段之一),然后计算它的可用性。因为在这种情况下,Gear 在存储在 line_item (start_date, end_date, start_hour, end_hour) 中的特定日期和时间租出......我没有在 Ruby 中进行大量高级查询,现在我没有确定我应该如何使用

齿轮模型中的可枚举,如下所示:

line_items.inject(0) {|line_item| line_item.where('line_items.cart_id' => NULL }

或者如果我可以像这样在齿轮模型中使用范围:

scope :availablegear, lambda { includes(:line_items).where('line_items.cart_id' => nil) }

我知道两者的语法可能都不正确,因此我可以就使用什么以及如何使用它提供一些指导。

谢谢。

我的项目使用 Rails 3.2.0、Ruby 1.9.4 和 MySQL

用建议的答案编辑

class Gear < ActiveRecord::Base
  attr_accessible :title, :size, :price, :sub_category_id, :user_id, :image, :image_a, :image_b, :image_c, :image_d, :image_e, :image_f, :image_g, :image_h, :image_i, :remote_image_url, :color, :year, :latefee, :cancellation, :minrental, :policy, :about, :address, :city, :state, :zip, :country, :latitude, :longitude, :gmaps
  ...some code omitted for brevity
  has_many :line_items
  scope :availablegear, joins(:line_items).where(:line_items => {:cart_id => nil})
  ...some code omitted for brevity

end

现在当我启动 Rails 控制台并执行 g = Gear.find(4) 然后执行 g.availablegear 时,我收到以下错误:NoMethodError: undefined method `availablegear' for #

【问题讨论】:

  • 您希望得到什么结果?齿轮或订单项?
  • 我正在尝试取回订单项

标签: ruby-on-rails ruby


【解决方案1】:

我认为您要查找的查询是

Gear.joins(:line_items).where(:line_items => {:cart_id => nil})

你可以把它放在Gear类的作用域中:

class Gear< ActiveRecord::Base
  scope :available, joins(:line_items).where(:line_items => {:cart_id => nil})
end

您可以在Rails Query Guide 中找到更多帮助(加入条件见 11.3)。

【讨论】:

  • 当我调用范围时,我不只是做类似 Gear.find(4).available 的事情吗? ....现在我在 Rails 控制台中遇到未定义的方法错误。我正在更新上面的代码
  • @DaveG 你像 Gear.available 这样使用它,你会得到一个包含至少一个 line_items 而没有 cart_id 的所有齿轮的关系。
【解决方案2】:

如果您想取回订单项:

class Gear < ActiveRecord::Base
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :gear

  scope :available, where(:cart_id => nil)
end

那你有装备就可以打电话

gear.line_items.available

这将返回属于 gear 并且没有 cart_id 的订单项。

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多