我创建了一个Ruby on Rails作业(从ActiveJob::Base
扩展),它解析CSV文件并将其行作为记录(Students
)插入数据库中。这是按预期工作的。
但是,当我尝试从数据库中获取另一个对象时(Career
为每个Student
,每个CSV行的一部分作为一对(career_code, career_name)
),我收到此错误:
undefined method 'find_by' for Career:Class
(我也尝试使用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 提前致谢
答案 0 :(得分:1)
代码职业生涯中任何机会都不是AR,而是其他一些课程?这至少可以解释为什么这些方法不存在。