设置a:has_many:通过在belongs_to关联Ruby on Rails上的关联

时间:2010-10-05 13:37:52

标签: ruby-on-rails ruby associations has-many-through belongs-to

我有三个模型,每个模型都有以下关联:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end

正如您在评论文章中所看到的,我已经提到了我需要的内容。

2 个答案:

答案 0 :(得分:8)

您只需创建访问它的方法

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

或者,您可以将model3s方法委托给model1

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end

答案 1 :(得分:0)

为什么不尝试:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
 belongs_to :model1
 has_many   :model3s, :primary_key => :model1_id,
                      :foreign_key => :model1_id

end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many   :model2s, :primary_key => :model1_id,  
                       :foreign_key => :model1_id
end

这将有一个有效的记录连接model2和model3 by model1_id将model1完全排除在外,应该更有效率。