2011-09-14 42 views
1

顯然我在這裏錯過了一些簡單的東西。這是我的兩個類和我打來的代碼。當我使用:include with find時,它會爆炸並在find行上給我一個NoMethodError。當我不使用:包括它工作得很好(但顯然沒有做加盟)使用時的NoMethodError:包含關聯的Rails 3與Active Record

稱爲碼

def index 
    @users = User.find(:all, :include => [:org]) 
end 

class User < ActiveRecord::Base 
    belongs_to :org, :primary_key => :org_id 
end 

class Org < ActiveRecord::Base 
    #define primary key because it is not :id 
    #because this table is in an old db 
    #that can't be changed 
    set_primary_key :org_id 

    has_one :user 

    def full_name 
     "#{emp_fname} #{emp_lname}" 
    end 
end 

確切的錯誤

NoMethodError(當你沒有想到它時,你有一個零對象! 您可能預期了Array的一個實例。 評估nil.each時出現錯誤:

+0

你的意思是用於組織有隻有一個用戶?組織和用戶之間是否存在1:1的關係?約定是主鍵被命名爲id。你爲什麼試圖使用org_id作爲org的主鍵? –

+0

users表是新的,org表位於我們用於讀取的遺留數據庫中。相信我,如果可以的話,我會改變PK名稱。 – joekarl

回答

0

您使用的是哪種版本的導軌?你的標籤說3 - 是3.1還是3.0.x系列之一?無論如何,它似乎在3.0.x中:包括散列語法findisn't supported

嘗試User.includes(:org).find(:all)

+0

是rails 3.0.10。我嘗試了你的建議並得到了同樣的錯誤。堆棧跟蹤中的最後一行是:activerecord(3.0.10)lib/active_record/association_preload.rb:159:在'set_association_single_records' – joekarl

0

好吧,經過大量的挖掘和反覆試驗,基本上它是一個表中的一個表和另一個表中不同的架構的組合。通過爲我們的活動記錄對象指定完全限定的表名,活動記錄停止自行拋出。

所以最終代碼:

稱爲碼

def index 
    @users = User.includes(:org) 
end 

class User < ActiveRecord::Base 
    set_table_name "DOC_REQUEST.USERS" 

    belongs_to :org, :primary_key => :org_id 
end 

class Org < ActiveRecord::Base 
    set_table_name "AOS.ORG" 

    #define primary key because it is not :id 
    #because this table is in an old db 
    #that can't be changed 
    set_primary_key :org_id 

    has_one :user 

    def full_name 
     "#{emp_fname} #{emp_lname}" 
    end 
end 
相關問題