2012-10-31 2 views
0

I가 다음과 같은 모델 클래스 ...NoMethodError 어디에요에게 (열망 가져 오는)

class Image < ActiveRecord::Base 
    attr_accessible :description, :title 
    has_many :imageTags 
    has_many :tags, :through => :imageTags 
end 

class Tag < ActiveRecord::Base 
    attr_accessible :name 
    has_many :imageTags 
    has_many :images, :through => :imageTags 
end 

class ImageTag < ActiveRecord::Base 
    attr_accessible :position 
    belongs_to :image 
    belongs_to :tag 
end 

를 사용하여 때이 ID로 태그를 가져 오기위한 find을 사용하는 경우 1

t = Tag.find(1); 
@images = t.images; 

그러나 때

t = Tag.where(:name => "foo"); 
@images = t.images; 
: 나는 where와 동일한 작업을 수행, 내가 설명 undefined method 'images'과 더불어, NoMethodError를 얻을 수

또한 .where 문 앞에 .includes(:images)을 추가하려고 시도했지만 작동하지 않습니다. 그럼 Images은 모두 Tag에 속합니다.

답변

3

.where은 단일 개체가 아니라 ActiveRecord :: Relation 인스턴스를 반환합니다. .first을 압수하여 반환되는 유일한 레코드 (아마도)를 얻습니다.

t = Tag.where(name: "foo").first 
@images = t.images 
+0

aaah! 말이 되네요 ... 고마워요! –