我的应用程序中有一个多态关联,用于跟踪应用程序中的订单。我希望能够查询Meal
这个模型:orderable
,但是由于某种原因,在添加关联后,对:valid?
的调用会引发错误。
class Order < ApplicationRecord
belongs_to :order_status
belongs_to :client
has_many :order_items
has_many :orderables, through: :order_items, source: :orderable, source_type: 'Meal'
end
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :meal, -> { where( order_items: { orderable_type: 'Meal' } ).includes(:meal) }, foreign_key: 'orderable_id'
belongs_to :orderable, polymorphic: true
validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
validate :order_present
validate :item_present
scope :are_veggies, -> { includes( :meal ).where( :meals => { type_of: 'veggie' }) }
scope :are_meals, -> { includes( :meal ).where.not( :meals => { type_of: 'veggie' }) }
private
def item_present
if orderable.present? and !orderable.active
errors.add(:orderable, "Selected item is not available.")
end
end
def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end
end
class Meal < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
has_many :tags, as: :taggable
has_many :order_items, as: :orderable
validates_presence_of :name, :type_of
default_scope { where(active: true) }
end
所有查询均正常运行,我可以致电Order.find(x).meals
。我可以打电话给Order.find(x).order_items.are_meals
。
但是当我尝试致电OrderItem.find(x).valid?
时,我看到一个错误:ActiveRecord::ConfigurationError: Can't join 'Meal' to association named 'meal'; perhaps you misspelled it?
。知道是什么原因造成的吗?
答案 0 :(得分:0)
我输入了错误的模型:
# This
belongs_to :meal, -> { where( order_items: { orderable_type: 'Meal' } ).includes(:meal) }, foreign_key: 'orderable_id'
# Should have been
belongs_to :meal, -> { where( order_items: { orderable_type: 'Meal' } ).includes(:order_items) }, foreign_key: 'orderable_id'