2013-09-24 5 views
0

난 내가 모델레일 정의되지 않은 열 방법은

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

테이블 제품을 가지고 있지만 내가 c를 레일을 실행할 때 내가 속성에 액세스 할 수 없습니다 이상한 문제가 있습니다.

제품 = 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 :: 관계 클래스? 방법은 어디에서 Product 클래스를 얻을 수 있습니까? 고맙습니다.

답변

2

우선 where은 (는) ActiveRecord 관계를 반환합니다. 간단히 말해서, 그것은 단지 실행되지 않은 액티브 레코드 쿼리입니다. 'order', 'where', 'joins'등의 쿼리를 체인화 할 수 있으며이 쿼리에서 반환 된 레코드에 액세스하려는 경우에만 쿼리가 평가됩니다.

그래서 당신이 무슨 짓을했는지 자연스럽게 실패

ActiveRecord::Relation.barcode했다.

어쨌든, 단지 product = Product.where("barcode='B0000000008'").first을하고 당신은 당신이 barcode

+0

가 작동 이제 감사 전화를 할 수있는 제품 개체를 얻을 수 있습니다 – Muflix

관련 문제