2011-05-05 46 views
1

我寫了下面的類:收到ActiveRecord的關係,但需要對象

class Occupation < ActiveRecord::Base 
    has_many :pref_labels 
    has_many :cv_occupations 
    has_many :cvs, :through => :cv_occupations 
    validates_uniqueness_of :uri 

    # This function will return the specified label for the given language. 
    def label(language = Language.find_or_create_by_code(:en)) 
    self.pref_labels.where("language_id = #{language.id}") 
    end 
end 

class PrefLabel < ActiveRecord::Base 
    belongs_to :language 
    belongs_to :concept 
    belongs_to :skill 
    belongs_to :occupation 
    validates_uniqueness_of :value, :scope => [:language_id, :value] 
    validates_uniqueness_of :language_id, :scope => [:language_id, :value] 
end 

在我看來,我把以下內容:%TD = occupation.label(@language) 但這種回報作爲錯誤:

undefined method `value' for #<ActiveRecord::Relation:0x80c8368> 

我怎樣才能得到真正的對象返回而不是關係?我知道這事做與延遲加載....

+0

後也控制器的操作代碼 – Bohdan 2011-05-05 13:23:39

回答

6

變化

self.pref_labels.where("language_id = #{language.id}") 

self.pref_labels.where("language_id = #{language.id}").all #or .first if you only one the first one 
+0

感謝,該訣竅。 – 2011-05-05 13:40:55

+1

in Rails 4'.all'現在也是一個關係。 '.first'仍然可以工作 – 2015-03-21 04:02:37

相關問題