0
我已經創建了一個Ruby on Rails作業(從ActiveJob::Base
開始),該作業解析CSV文件並將其行作爲記錄(Students
)插入到數據庫中。這是按預期工作的。
然而,當我嘗試從DB(在Career
每個Student
,這是每個CSV行的部分作爲一對(career_code, career_name)
)取另一個目的,我發現了這樣的錯誤:無法從Rails作業中的數據庫查找對象
undefined method 'find_by' for Career:Class
(I也嘗試使用Career.where
代替)。
我覺得這很奇怪,因爲我已經保存了我的學生,這也是一個ActiveRecord::Base
子類。
這裏是我的工作的相關部分:
ActiveRecord::Base.transaction do
student_hash.keys.each do |k|
some_student = student_hash[k]
student = Student.new
student.csv_id = some_student.id
student.first_name = some_student.first_name
student.last_name = some_student.last_name
student.file_number = some_student.file_number
# student.career = Career.where(code: some_student.career_code)
student.career = Career.find_by code: some_student.career_code
puts student.save! # Why this works, and the above line doesn't?
end
end
而且也,所需的輸出,因爲我可以看到它在Rails的控制檯:
Loading development environment (Rails 4.2.4.rc1)
2.1.3 :001 > Career.where(code: 11)
Career Load (0.5ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? [["code", 11]]
=> #<ActiveRecord::Relation [#<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>]>
2.1.3 :002 > Career.where code: 11
Career Load (0.2ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? [["code", 11]]
=> #<ActiveRecord::Relation [#<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>]>
2.1.3 :003 > Career.find_by code: 11
Career Load (0.4ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? LIMIT 1 [["code", 11]]
=> #<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>
2.1.3 :004 >
也許這是一個非常愚蠢的問題,但我是一個使用Rails的初學者。我是否需要導入某種「上下文」(這似乎不太可能,因爲學生似乎已經得到妥善解決)?順便說一句,我使用的是Rails 4.2.4.rc1。
在此先感謝
行'student.career = Career.where(代碼:some_student.career_code)'工作,如果你做'Career.where(代碼:some_student.career_code).first'? '.where'返回一個Active Record Relation對象,它充當AR對象的集合,您可以繼續將數據庫查詢方法鏈接到該對象上。 –
@JakeKaad對不起,也沒有工作。無論如何,這不等於使用'find_by'嗎? – jmm
代碼「Career」中的任何機會都不是AR,而是其他一些類?這至少可以解釋爲什麼這些方法不存在。 –