收到ActiveRecord Relation,但需要对象

cod*_*nny 1 ruby lazy-loading ruby-on-rails

我写了以下课程:

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
Run Code Online (Sandbox Code Playgroud)

在我看来,我调用以下内容:%td = occup.label(@language) 但这会返回错误:

undefined method `value' for #<ActiveRecord::Relation:0x80c8368>
Run Code Online (Sandbox Code Playgroud)

如何获取所返回的actuall对象而不是关系?我知道这与延迟装载有关....

Srd*_*jic 6

更改

self.pref_labels.where("language_id = #{language.id}")
Run Code Online (Sandbox Code Playgroud)

self.pref_labels.where("language_id = #{language.id}").all #or .first if you only one the first one
Run Code Online (Sandbox Code Playgroud)