最后使用自定义列名称

时间:2012-09-01 14:13:17

标签: ruby-on-rails activerecord ruby-on-rails-3.2

我的模型定义如下:

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 ::错误:'where'中的未知列'inseminations.animal_id'   子句':SELECT inseminations。* FROM inseminations WHERE   inseminationsanimal_id = 1 ORDER BY inseminationsid DESC   限制1

如何在cow_id和/或bull_id列中将其指定为searh?这可能吗?

提前致谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以指定外键:

has_many :inseminations, :foreign_key => :bull_id

但是你只能有一个foreign_key,所以它不适用于奶牛。

您可以执行Rails Model has_many with multiple foreign_keys之类的操作来使其发挥作用。但在这种情况下,你需要:

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

和类似于授精&lt;&lt;,inseminations =等等。