0

我有以下型号:

class Mark < ActiveRecord::Base
  validates_presence_of :user
  validates_presence_of :page

  belongs_to :user

  has_many :mettings
  has_many :tags,   :through => :mettings
  has_many :terms,  :through => :mettings
end


class Metting < ActiveRecord::Base
  belongs_to :mark
  belongs_to :user

  belongs_to :tags,  :foreign_key => :metum_id, :class_name => "Metum"
  belongs_to :terms, :foreign_key => :metum_id, :class_name => "Metum"
end


class Metum < ActiveRecord::Base
  validates_presence_of   :type
  validates_presence_of   :name

  has_many    :mettings
  has_many    :marks, :through => :mettings

end


class Tag < Metum

end

class Term < Metum

end

问题是,当我查找标记或Metting 的“标签”或“术语”时,我会得到该标记或Metting 的所有“标签”“术语”。例如:

>> met = Metting.find(9)
  Metting Load (0.3ms)  SELECT `mettings`.* FROM `mettings` WHERE `mettings`.`id` = 9 LIMIT 1
=> #<Metting id: 9, mark_id: 1, metum_id: 1, user_id: 1, created_at: "2011-10-31 10:53:01", updated_at: "2011-10-31 10:53:01">
>> met.tags
  Metum Load (0.3ms)  SELECT `meta`.* FROM `meta` WHERE `meta`.`id` = 1 LIMIT 1
=> #<Term id: 1, type: "Term", name: "Authority", created_at: "2011-10-30 22:32:35", updated_at: "2011-10-30 22:32:35">
>> met.terms
  Metum Load (0.3ms)  SELECT `meta`.* FROM `meta` WHERE `meta`.`id` = 1 LIMIT 1
=> #<Term id: 1, type: "Term", name: "Authority", created_at: "2011-10-30 22:32:35", updated_at: "2011-10-30 22:32:35">

在这种情况下,Metting 只有一个与之关联的术语而不是标签。rails 生成的查询没有使用“Metum”中的“type”列来区分标签和术语。有什么想法可以解决这个问题,以便在上述调用中只返回标签和术语?

谢谢。

4

2 回答 2

2

您需要在 :class_name 属性中正确设置类型。以机智:

belongs_to :tags,  :foreign_key => :metum_id, :class_name => "Tag"
belongs_to :terms, :foreign_key => :metum_id, :class_name => "Term"

否则 AR 将不知道如何解析 STI 子类型,并将在基类上执行查找。

于 2011-10-31T17:56:00.690 回答
1

您可以像这样为您的关系添加条件:

belongs_to :tags,
           :foreign_key => :metum_id,
           :class_name => "Metum",
           :conditions => ['type = ?', 'Tag']

belongs_to :terms,
           :foreign_key => :metum_id,
           :class_name => "Metum",
           :conditions => ['type = ?', 'Term']
于 2011-10-31T17:29:59.337 回答