【问题标题】:Using find_by_<field> returns "Table doesn't exist" error使用 find_by_<field> 返回“表不存在”错误
【发布时间】:2014-03-20 16:23:15
【问题描述】:

我正在开发一个连接到 SQL Server 2008 数据库的 Ruby 1.8 / Rails 2.1 应用程序。

当我尝试使用find_by_CompanyCode 方法时,ActiveRecord 返回 NoMethodError。然而,从下面你可以看到该表存在并且有问题的方法。

不知道我错过了什么......任何帮助将不胜感激

编辑:当我刚刚运行 IvantageEmployee.first 时,只有以“代码”结尾的字段才不会出现 .. 视图发生错误。将完全相同的代码移至控制器,代码按预期工作。

eval @goal.organization_type.employee_class + ".find_by_#{@goal.organization_type.employee_field_code}('#{@goal.specifier}').#{@goal.organization_type.employee_field_description}" >> IvantageEmployee.first.CompanyCode => “盖伊” >> IvantageEmployee.find_by_CompanyCode('GAI') NoMethodError:IvantageEmployee 的未定义方法“find_by_CompanyCode”(表不存在):类 来自 /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1613:in `method_missing_without_paginate' 来自 /usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.15/lib/will_paginate/finder.rb:170:in `method_missing' 来自 (irb):7 >>

更多信息。该表有几个字段。我正在努力解决的是 CompanyCode,但它也有 RegionDescription。

注意以下控制台输出。 find_by_RegionDescription 有效; find_by_CompanyCode 不起作用。另外,当我刚刚输出类时,CompanyCode 没有出现,但是 RegionDescription 不确定为什么 ActiveRecord 会丢失表上的字段

>> IvantageEmployee.find_by_RegionDescription 'GAI' ### 查找方法 find_by_RegionDescription => 无 >> IvantageEmployee.find_by_CompanyCode 'GAI' ### 查找方法 find_by_CompanyCode NoMethodError:IvantageEmployee 的未定义方法“find_by_CompanyCode”(表不存在):类 来自 /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1614:in `method_missing_without_paginate' 来自 /usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.15/lib/will_paginate/finder.rb:170:in `method_missing' 来自 (irb):9 >>

【问题讨论】:

  • 不是一个修复程序,但我将最初导致此错误的代码从视图移到了控制器,并且它起作用了。不知道为什么。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

你需要使用蛇皮而不是骆驼皮:

IvantageEmployee.find_by_company_code('GAI')

ruby 中的约定是对类使用驼峰式大小写,对方法使用蛇形大小写。 Rails 遵循该约定(您也应该如此),因此您可以假设由它动态创建的任何方法都将是蛇形案例。

【讨论】:

  • 我希望你是对的。但我也认为 ActiveRecord 可能会在“finds_by_”之后附加文本作为列名。 CompanyCode 不是一个类;这是列名。 &gt;&gt; IvantageEmployee.first.CompanyCode =&gt; "GAI" &gt;&gt; IvantageEmployee.find_by_company_code('GAI') NoMethodError: undefined method find_by_company_code' for IvantageEmployee(表不存在):来自 /usr/lib/ruby/gems/1.8/gems/activerecord- 2.1.0/lib/active_record/base.rb:1613 的类:in method_missing_without_paginate' from /usr/lib/ruby/gems/1.8/gems/will_paginate- >>
猜你喜欢
  • 2021-01-01
  • 1970-01-01
  • 2011-05-11
  • 2021-09-15
  • 2020-09-30
  • 2022-07-08
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
相关资源
最近更新 更多