Rails 4 first_or_initialize sql double id "_id_id" sql 由 Arel 生成

Rails 4 first_or_initialize sql double id "_id_id" sql generated by Arel

我有一个简单的 Rails 4 first_or_initialize,它根据下面 tender.rb 文件中的注释在富连接 table 中创建条目。

# == Schema Information
#
# Table name: tenders
#
#  id                 :integer          not null, primary key
#  project_id         :integer          not null
#  company_id         :integer          not null
#  tender_awarded_at  :date
#
# Indexes
#
#  index_tenders_on_company_id          (company_id)
#  index_tenders_on_project_id          (project_id)

class Tender < ActiveRecord::Base
  belongs_to :project_id
  belongs_to :company_id
end

csv = CSV.new(data, {headers: true, header_converters: :symbol, col_sep: ','})
  csv.each do |line|
    unless line[:project_id].blank?
      project_id = line[:project_id].to_i
      company_id = line[:company_id].to_i
      tender = ::Tender.where(:project => project_id, :company => company_id).first_or_initialize

此脚本适用于仅通过匹配一个主键来导入的其他导入。这是通过匹配两个非主键列创建的。

PG::UndefinedColumn at /imports/tender
ERROR:  column tenders.project_id_id does not exist
LINE 1: SELECT  "tenders".* FROM "tenders" WHERE "tenders"."project

看起来 sql 是由 Arel @value 实例变量中的名称设置的。在此之前我在任何地方都看不到它。

<Arel::Nodes::Equality:0x007f8dd0d22318 @left=#<struct Arel::Attributes::Attribute relation=#<Arel::Table:0x007f8dd0ccb6d0 @name="tenders", @engine=Tender(id: integer, project_id: integer, company_id: integer, tender_awarded_at: date), @columns=nil, @aliases=[], @table_alias=nil, @primary_key=nil>, name="project_id_id">

有什么解决办法吗?

class Tender < ActiveRecord::Base
  belongs_to :project_id
  belongs_to :company_id
end

那是你的问题,你没有指向列,你指向 model/classes,正确的方法是

class Tender < ActiveRecord::Base
  belongs_to :project
  belongs_to :company
end

始终尝试将这些关联理解为英语,这会有意义,这里有一些示例

belongs_to :project # cause it's one
has_one :project
has_many :projects # cause it's many