我使用的是Rails 5.1。当有一系列"belongs_to“关联时,我该如何编写一个查找器方法呢?我有以下模型..。
class Plan < ApplicationRecord
...
has_many :plan_items, :dependent => :destroy
class PlanItem < ApplicationRecord
...
belongs_to :offer, :optional => false
class Offer < ApplicationRecord
belongs_to :package, :optional => false
class Package < ApplicationRecord
has_and_belongs_to_many :items我想写一个查找器,获得与id = "blah“的项目的所有计划。但是下面是失败的.
[19] pry(main)> Plan.joins(plan_items: :offer).joins(packages: :item).where(:item => {:id => "abac"}).count
ActiveRecord::ConfigurationError: Can't join 'Plan' to association named 'packages'; perhaps you misspelled it?
from /Users/davea/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2.1/lib/active_record/associations/join_dependency.rb:188:in `find_reflection'当有一系列belongs_to关联链时,我该如何编写查找器?
发布于 2020-01-15 10:30:47
首先,可能您的表名是错误的。其次,要在委托关联之间传递方法,可以使用belong_to
发布于 2020-01-15 06:50:58
我假设PlanItem是Plan和Item之间的连接表(这将符合Rails命名约定)。这可以通过through关联和作用域很好地完成。我会这样做..。
class Plan < ApplicationRecord
has_many :plan_items, dependent: :destroy
has_many :items, through: :plan_items
scope :blah_items { items.id_of_blah }
class PlanItem < ApplicationRecord
belongs_to :offer, optional: false
belongs_to :item
class Item < ApplicationRecord
scope :id_of_blah { where(id: 'blah') }然后你可以这样叫它。Plan.with_blah_items,或者如果您有计划的活动记录集合,则可以使用作用域将其范围缩小到plans.with_blah_items。
由于ActiveRecord关联将返回ActiveRecord关系,您可以将它们与任何其他活动记录方法链接在一起(例如,Plan.first.items.where(item: { id: 'blah' })作用域只是让它变得更好和整洁。:)
如果PlanItem不是计划和项目之间的连接表,您应该做的第一件事就是重命名它。这不仅仅是一种最佳实践,rails花费了大量时间来假定事物的名称,这可能会导致错误。重命名后,应在名为PlanItem的计划和项目之间创建一个连接表。如果这些表之间的连接对您的应用程序架构没有意义,您可以始终将through关联串在一起,但这将是一种代码味道。
如果你不想打乱作用域,你总是可以像这样做一个查询plan.items.where(items: { id: 'blah' })。
希望这能有所帮助!
https://stackoverflow.com/questions/59742388
复制相似问题