2013-09-24 20 views
0

我有奇怪的問題,我有表產品型號Rails的未定義列方法

class Product < ActiveRecord::Base 
    attr_accessible :id, :category_id, :name, :barcode, :price, ... 

但是當我運行軌道ç我有沒有屬性的訪問。

產品= Product.where( 「條形碼= 'B0000000008'」)

Product Load (22.5ms) EXEC sp_executesql N'SELECT [products].* FROM [products] WHERE (barcode=''B0000000008'')' 

=> [#<Product id: 8, category_id: 2, name: "Aplikovaná boj. umění (1 hodina)", barcode: "P0000000008", price: #<BigDecimal:362f9c8,'0.95E2',9(36)>, ... ] 

>> product.name 
=> "Product" 

>> product.class 
=> ActiveRecord::Relation 

>> product.barcode 
!! #<NoMethodError: undefined method `barcode' for #<ActiveRecord::Relation:0x00000003a354c8>> 

>> product.id 
!! #<NoMethodError: undefined method `id' for #<ActiveRecord::Relation:0x00000003a354c8>> 

>> product.price 
!! #<NoMethodError: undefined method `price' for #<ActiveRecord::Relation:0x00000003a354c8>> 

,但即時通訊能夠運行

>> product = Product.new 
>> product.name = "xx" 
=> "xx" 
>> product.class 
=> Product(id: integer, ...) 

最新產品類之間差異和ActiveRecord ::關係類?我如何從哪裏獲得產品類的方法?謝謝

回答

2

首先,where返回一個ActiveRecord關係。簡而言之,它只是未執行的活動記錄查詢。你可以鏈接像「訂單」,另一個「where」,「加入」等查詢,並且只有當你想訪問這個查詢返回的記錄時,纔會對查詢進行評估。

所以,你做了什麼是

ActiveRecord::Relation.barcode這自然會失敗。

反正,只是做product = Product.where("barcode='B0000000008'").first,你會得到你的產品對象,你可以調用barcode

+0

謝謝你,現在它的工作原理 – Muflix