2015-03-25 15 views
0

我有一個簡單的Rails 4 first_or_initialize,它根據下面的tender.rb文件中的註釋在富連接表中創建條目。Rails 4 first_or_initialize sql double id「_id_id」由Arel生成的sql

# == 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

可以從促使我看一下我剛纔說的問題上'tender.rb'其中的關係模型 – 2015-03-25 07:02:29

+0

嗯加入協會。我現在可以看到我已經添加了'belongs_to:project_id'而不是'belongs_to:projects'。這可能是原因。我會解決它。 – 2015-03-25 07:06:47

回答

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 
+0

當答案如此愚蠢簡單時,我既愛又恨,謝謝你的第二套眼睛。 – 2015-03-25 07:09:33