我有一个简单的Rails 4 first_or_initialize,它根据下面的tender.rb文件中的注释在富连接表中创建条目。
# == 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">
任何想法如何解决这个问题?
答案 0 :(得分:2)
class Tender < ActiveRecord::Base
belongs_to :project_id
belongs_to :company_id
end
那是你的问题,你没有指向专栏,你指的是模型/类,正确的方法是
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