0

我的模型定义如下:

class Animal < ActiveRecord::Base
    mount_uploader :picture, PictureUploader

    attr_accessible :picture, :born_date, :father_id, :mother_id, :name, :obs, :earring, :animal_type, :animal_type_id, :inseminations

    validates :name, :born_date, :presence => true
    validates :earring, :presence => true, :if => :should_have_earring?

    belongs_to :father, :class_name => "Animal"
    belongs_to :mother, :class_name => "Animal"
    belongs_to :animal_type
    has_one :birth

    has_one :sell
    has_one :death

    has_many :inseminations
end

class Insemination < ActiveRecord::Base
  attr_accessible :bull_id, :cow_id, :done, :expected_birth_date, :expected_dry_date, :insemination_date, :obs, :rut

  validates :bull_id, :presence => true
  validates :cow_id, :presence => true
  validates :insemination_date, :presence => true

  belongs_to :bull, :class_name => "Animal"
  belongs_to :cow, :class_name => "Animal"

  has_one :birth
  has_one :abortion
  has_one :dry
end

好,在某个地方,我想从某种动物身上进行最后一次授精……所以,我这样做@animal.inseminations.last了,它应该可以工作,但是,它使用animal_id授精模型中不存在的属性进行选择。所以我收到这样的错误:

Mysql2::Error:'where 子句'中的未知列'inseminations.animal_id':SELECT inseminations.* FROM inseminations WHERE inseminationsanimal_id= 1 订购方式inseminationsidDESC 限制 1

如何指定它来搜索cow_id和/或bull_id列?那可能吗?

提前致谢。

4

2 回答 2

2

我认为你有几个不同的选择:

1)而不是使用has_many :inseminations,创建两个单独的有很多关系:

has_many :cow_inseminations, :class_name => 'Insemination', :foreign_key => 'cow_id'
has_many :bull_inseminations, :class_name => 'Insemination', :foreign_key => 'bull_id'

2) 使用 STI 并创建 Animal 的子类。您需要向 Animal 添加一个类型字段才能使其工作:

class Cow < Animal
  has_many :inseminations, :foreign_key => 'cow_id'
end

class Bull < Animal
  has_many :inseminations, :foreign_key => 'bull_id'
end

然后你可以做 Bull.first.inseminations 或 Cow.first.inseminations

于 2012-09-01T14:26:16.707 回答
1

您可以指定外键:

has_many :inseminations, :foreign_key => :bull_id

但是你只能有一个foreign_key,所以它对奶牛不起作用。

您可以使用多个foreign_keys 执行Rails Model has_many之类的操作以使其正常工作。但是在这种情况下,您需要:

has_many :bull_inseminations, :foreign_key => :bull_id
has_many :cow_inseminations, :foreign_key => :cow_id

def inseminations
  # not sure how you store animal type, but something like
  return bull_inseminations if animal_type == "bull"
  return cow_inseminations if animal_type == "cow"
end

对于其他属性方法,如果您想使用它们,您将需要做类似的事情,例如:

def inseminations_changed?
  bull_inseminations_changed? or cow_inseminations_changed?
end

与 inseminations<<, inseminations= 等类似。

于 2012-09-01T14:24:03.013 回答