在Rails應用程序,我有一個模型,Machine
,包含以下命名範圍:爲什麼Rails命名範圍返回空(未初始化?)對象?
named_scope :needs_updates, lambda {
{ :select => self.column_names.collect{|c| "\"machines\".\"#{c}\""}.join(','),
:group => self.column_names.collect{|c| "\"machines\".\"#{c}\""}.join(','),
:joins => 'LEFT JOIN "machine_updates" ON "machine_updates"."machine_id" = "machines"."id"',
:having => ['"machines"."manual_updates" = ? AND "machines"."in_use" = ? AND (MAX("machine_updates"."date") IS NULL OR MAX("machine_updates"."date") < ?)', true, true, UPDATE_THRESHOLD.days.ago]
}
}
此命名範圍工作在發展模式的罰款。但是,在生產模式下,它會按預期返回2個模型,但模型爲空或未初始化;即返回實際對象(不是nil
),但所有字段都是nil
。例如,檢查控制檯的命名範圍的返回值時,將返回以下:
[#<Machine >, #<Machine >]
但是,正如你所看到的,返回的對象的所有字段設置爲nil
。
生產和開發環境基本相同。兩者都使用SQLite數據庫。以下是爲查詢生成的SQL語句:
SELECT
"machines"."id",
"machines"."machine_name",
"machines"."hostname",
"machines"."mac_address",
"machines"."ip_address",
"machines"."hard_drive",
"machines"."ram",
"machines"."machine_type",
"machines"."use",
"machines"."comments",
"machines"."in_use",
"machines"."model",
"machines"."vendor_id",
"machines"."operating_system_id",
"machines"."location",
"machines"."acquisition_date",
"machines"."rpi_tag",
"machines"."processor",
"machines"."processor_speed",
"machines"."manual_updates",
"machines"."serial_number",
"machines"."owner"
FROM
"machines"
LEFT JOIN
"machine_updates" ON "machine_updates"."machine_id" = "machines"."id"
GROUP BY
"machines"."id",
"machines"."machine_name",
"machines"."hostname",
"machines"."mac_address",
"machines"."ip_address",
"machines"."hard_drive",
"machines"."ram",
"machines"."machine_type",
"machines"."use",
"machines"."comments",
"machines"."in_use",
"machines"."model",
"machines"."vendor_id",
"machines"."operating_system_id",
"machines"."location",
"machines"."acquisition_date",
"machines"."rpi_tag",
"machines"."processor",
"machines"."processor_speed",
"machines"."manual_updates",
"machines"."serial_number",
"machines"."owner"
HAVING
"machines"."manual_updates" = 't'
AND "machines"."in_use" = 't'
AND (MAX("machine_updates"."date") IS NULL
OR MAX("machine_updates"."date") < '2010-03-26 13:46:28')
任何想法發生了什麼問題?
不知道,但在':select'和':group'中,你可以只用'machines。*',不是? – glebm 2010-04-02 19:02:07
你是否檢查過由此產生的SQL? – ryeguy 2010-04-09 13:42:11
我有,現在我發佈了生成的SQL。 – mipadi 2010-04-09 13:46:58