2016-04-15 43 views
0

您好我想使用連接來匹配兩個實體。帶連接的查詢中未初始化的常量

預期的結果:

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

您有'BoughtDetail'模型和'BoughtDetail'和'EntryType'之間的已定義關係嗎? – Babar

+0

@Babar更新後。 –

回答

1

你上哪兒去定義你的@sum_earnings?

你有沒有試着寫

Backend::EntryType.joins(:bought_details).sum(:price) 
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