ruby-on-rails – 设置a:has_many:通过belongs_to关联Ruby on Rails上的关联

我有三个模型,每个模型都有以下关联:
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

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

解决方法

您只需创建访问它的方法
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...