2012-07-29 62 views
0

我正在學習Rails 3中的'where',我想知道爲什麼我的代碼給了我一個NoMethod錯誤。Rails 3:查詢問題

def create 
    #get form values from 'new' page 
    @post = Post.new(params[:post]) 

    #search for the inventory item with the sku code the user typed in the form 
    @item = Inventory.where(:sku_code => @post.sku_code) 

    #set post variable to a variable from the row with the sku code 
    @post.detail = @item.detail 

    @post.save 
    end 

通過搜索SKU,我想檢索相同ID中的其他變量並將它們設置爲我的@post變量。任何人都可以幫我一把嗎?

回答

1

假設SKU代碼都是唯一的,你必須做這樣

@post = Post.new(params[:post]) 

@post.detail = Inventory.where(:sku_code => @post.sku_code).first.try(:detail) 

first將獲取第一個(可能只)記錄在數據庫中。如果返回的Inventory不爲零,則try將嘗試獲取detail

檢查this blog post以瞭解有關try方法的更多信息。

+0

感謝您的回覆。我檢查了參考文獻,他們是正確的。它給我一個模板缺少錯誤: 缺少模板帖子/創建,應用程序/創建。 任何想法? – jbearden 2012-07-29 07:53:16

+0

通常您想在創建後重定向,例如顯示操作。或者如果帖子無法保存,則通過渲染新的形式再次顯示錶單。另請參閱http://guides.rubyonrails.org/getting_started.html#creating-new-posts – iltempo 2012-07-29 08:56:37

+0

我懂了它的工作原理!謝謝!!! – jbearden 2012-07-29 22:02:11