2012-07-11 65 views
0

我對rails比較陌生,認爲我的問題可能部分是由於我對Ruby類的性質和範圍以及它們產生的對象缺乏清晰的理解。調用ID爲零 - 實例方法

我收到以下錯誤:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

Rails.root: /Users/rmcnairn/rails/search 
Application Trace | Framework Trace | Full Trace 

app/models/photo.rb:17:in `scanner' 
app/controllers/suppliers_controller.rb:66:in `block in update' 
app/controllers/suppliers_controller.rb:65:in `update' 

照片記錄的創建後。我希望使用該新記錄來引用關聯的記錄(Fabric),並在該記錄上調用實例方法(Scan)。 掃描在Fabric類中定義。

我的記錄設置,使 一個照片 *的has_many * 面料通過Fabric_Photos

這是我的照片級的快照,我試圖找到這個協會,並調用掃描方法就可以了。

class Photo < ActiveRecord::Base 

    has_many :fabrics, :through => :fabric_photos 
    has_many :fabric_photos 
    after_create :scanner 
    accepts_nested_attributes_for :fabrics 
    mount_uploader :image, ImageUploader 


    def scanner 
    if self.fabric == true #fabric is a boolean column in the Photo table 
     self.fabrics.first.scan 
    else 
    return 
    end 
    end 
end 

編輯 我已經加入了相關供應商的控制器代碼 供應商have_many面料,面料有許多照片

def update 
    @supplier = Supplier.find(params[:id]) 

    respond_to do |format| # line 65 
     if @supplier.update_attributes(params[:supplier]) 
     format.html { redirect_to suppliers_url, notice: @supplier.name.to_s + ' was updated' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit", notice: @supplier.name.to_s + ' was NOT updated' } 
     format.json { render json: @supplier.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

有沒有可能讓你幫助我瞭解多一點有關的性質我調用的關聯對象和限制,如果有的話放在另一個類的調用方法上。

我猜想

self.fabrics.first 

正在恢復的東西是不能擁有.scan調用它的方法。如果有人向我解釋Active Record實際上在這裏產生什麼,那將會很棒。

非常感謝

+0

您粘貼了堆棧跟蹤,並且其中引用的控制器未發佈......始終從堆棧跟蹤中發佈相關代碼以獲取更好的答案:) – Draiken 2012-07-11 16:19:18

+0

剛剛添加了控制器代碼! :) – RMcNairn 2012-07-11 17:20:45

回答

4

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

的問題是,self.fabrics.first將返回零。在底層數據庫中,這意味着由Rails生成的sql查詢返回null。

我會看看控制器代碼,或者你用來創建模型的任何東西。您可能不會保存/更新相關模型以連接所有內容。另外,請查看每個表格和記錄中的記錄的ID,以查看自己正在創建和未創建的內容。

在數據庫中,您應該看到如果您運行rails生成的sql代碼(查看日誌),那麼在結構表中沒有符合查詢條件的內容。

+1

你是正確的,它看起來好像問題實際上是坐在我的Fabric控制器中,我開始通過手動更新和保存每個模型中記錄的屬性直到它損壞。非常感謝! – RMcNairn 2012-07-11 20:31:23