我是Rails的新手,并从Rails 3.2升级到Rails 4.0。我一直在尝试升级之前从未见过的以下错误:
Mysql2::Error: Unknown column 'report_fields.id' in 'order clause': SELECT rrf.* FROM `report_fields` JOIN report_types rrt ON rrt.id = rrf.report_type_id WHERE (rrt.name = 'Creturn' AND rrf.name = 'Root Cause') ORDER BY `report_fields`.`id` ASC LIMIT 1 (ActiveRecord::StatementInvalid)
我查看了stackoverflow上的几个相关帖子,但找不到解决方案。他们中的大多数都在做db changes/migration,但我不更改表格中的任何内容。
当我在report_fields表上运行show table命令时,我可以看到id字段就在那里。我只是不明白为什么找不到它。
show fields from report_fields;
Field Type Null Key Default Extra
id int(11) NO PRI auto_increment
report_type_id int(11) NO MUL
name varchar(255) NO
parent_id int(11) YES MUL
display_order smallint(6) NO 0
ReportField类:
class ReportField < ActiveRecord::Base
acts_as_tree
has_many :report_field_values
has_many :report_field_options, -> { order(:value) }
belongs_to :researchable_report_type
# THIS IS WHERE THE ERROR COMES FROM
def self.find_field_for_report_type(report_type, field_name)
return ReportField.find(
:first,
:select => "rrf.*",
:joins => "AS rrf
JOIN report_types rrt
ON rrt.id = rrf.report_type_id",
:conditions => ["rrt.name = ? AND rrf.name = ?",
report_type, field_name])
end
ReportType类:
class ReportType < ActiveRecord::Base
has_many :report_fields, -> { order(:display_order) }
def self.load_by_name(rrt_name,report_name = nil)
self.find(:first,
:include => [:report_fields => :report_field_options],
:conditions => {:name => rrt_name,:report_name => report_name})
end
........
end
我知道Rails 4弃用了很多finder方法,所以我在Gemfile中包含了Gem“activerecord-deprecated_finders”,但它可能不相关......
这个问题的根本原因是什么?我应该在哪里看看?
更新 从理论上讲,activerecord-deprecated_finders gem应该启用旧的finder方法,但为了以防万一,我使用Rails 4重写了查询,但我仍然遇到类似的错误。
新查询:
def self.find_field_for_report_type(report_type, field_name)
return ReportField.joins("JOIN report_types ON report_types.id = report_field.report_type_id")
.where("report_types.name = '#{report_type}' AND report_field.name = '#{field_name}'")
.first
end
这次它在report_fields表中抱怨未知列'name'。同样,名称栏就在那里......
更多更新: 调用ReportFields.last并打印出来,我有以下日志:
[DEBUG] ReportField Load (69.0ms) SELECT `report_fields`.* FROM `report_fields` ORDER BY `report_fields`.`id` DESC LIMIT 1
[INFO] #<ReportField:0x007fa271514e18>#<ReportField:0x007fa271514e18>
[INFO] 200, Action Required
2016-08-16更新 看起来这与表别名有关。当我取出表别名时,查询实际上有效。不知道发生了什么......
def self.find_field_for_report_type(report_type, field_name)
return ReportField.find(
:first,
:select => "*",
:joins => "JOIN report_types
ON report_types.id = report_fields.report_type_id",
:conditions => ["report_types.name = ? AND report_fields.name = ?",
report_type, field_name])
end