您好我想使用连接来匹配两个实体。
预期结果:
select sum(price) from entry_types inner join bought_details on entry_types.id = bought_details.entry_type_id
现在我有:
@sum_earnings = EntryType.joins(:bought_details).sum(:price)
有一个错误:
uninitialized constant EntryType::BoughtDetail
架构信息:
# Table name: bought_details
#
# id :integer not null, primary key
# bought_data :date not null
# end_on :date not null
# entry_type_id :integer
# person_id :integer
# start_on :date
# Table name: entry_types
#
# id :integer not null, primary key
# kind :string not null
# kind_details :string not null
# description :text
# price :decimal(5, 2) not null
如何解决此问题?这个错误是什么意思?提前谢谢。
型号:
class Backend::EntryType < ActiveRecord::Base
has_many :bought_details
end
class Backend::BoughtDetail < ActiveRecord::Base
belongs_to :entry_type
end
答案 0 :(得分:1)
您在哪里定义了@sum_earnings?
你有没有尝试过写作
Backend::EntryType.joins(:bought_details).sum(:price)
答案 1 :(得分:1)
您的模型是命名空间。尝试使用关系明确提及类:
class Backend::EntryType < ActiveRecord::Base
has_many :bought_details, class_name: 'Backend::BoughtDetail'
end
class Backend::BoughtDetail < ActiveRecord::Base
belongs_to :entry_type, class_name: 'Backend::EntryType'
end