当类似的代码在别处工作时,为什么Rails会产生这个SQL错误?

时间:2014-08-20 20:27:10

标签: ruby-on-rails ruby rake

我有这个rake任务来导入我正在尝试调试的csv文件,使用类似的模式在文件中每行的8个不同表中创建记录。创建独立表中的记录,然后我需要找到这些记录的id号,以用作外键在依赖表中创建记录。

错误说:

rake aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BLANCO) LIMIT 1' at line 1: SELECT  `fields`.* FROM `fields`  WHERE (IGNACIO BLANCO) LIMIT 1

我在MySQL控制台中验证过。但是在之前的五个表中,这个类似的代码可以很好地获取外键:

require 'csv'

    CSV.foreach('public/partial.csv', :headers => true) do |row|
        # create the Company object
        this_company_name = row['name'].strip!
        this_operator_num = row['operator_num']        
        if !(Companies.exists?(:company_name => this_company_name))
          Companies.create(company_name: this_company_name, operator_num: this_operator_num)
        end
        thecompany = Companies.find_by(company_name: this_company_name)
        company_id = thecompany.id

        # create the County object
        this_county_name = row['county'].strip!
        if !(Counties.exists?(county_name: this_county_name))
          Counties.create(county_name: this_county_name)
        end
        thecounty = Counties.find_by(county_name: this_county_name)
        county_id = thecounty.id

        # create the Gastype object  
        this_gastype_name = row['gas_type'].strip!
        if !(Gastypes.exists?(gas_type: this_gastype_name))
          Gastypes.create(gas_type: this_gastype_name)
        end
        thegastype = Gastypes.find_by(gas_type: this_gastype_name)
        gastype_id = thegastype.id

        # create the Field object
        this_field_name = row['field_name'].strip!
        this_field_code = row['field_code'].strip!
        if !(Fields.exists?(field_name: this_field_name))
          Fields.create(field_name: this_field_name, field_code: this_field_code)
        end
        thisfield = Fields.find_by(this_field_name)
        field_id = thisfield.id
...

Rails创建的产生错误的SQL语句是:

SELECT  `fields`.* FROM `fields`  WHERE (IGNACIO BLANCO) LIMIT 1;

有明显不正确的WHERE子句。我的问题是为什么Rails没有产生正确的陈述,如:

SELECT fields。* FROM fields WHERE(field_name ='IGNACIO BLANCO')LIMIT 1;

我应该更改.find_by语句的写法吗?或者有更好的方法来获得必要的外键吗?

1 个答案:

答案 0 :(得分:3)

由于这一行:

thisfield = Fields.find_by(this_field_name)

您只是将字符串传递给find_by,Rails会将其视为原始SQL。

您需要使用以下两种解决方案之一:

thisfield = Fields.find_by_field_name(this_field_name)
thisfield = Fields.find_by(field_name: this_field_name)