在belongs_to关联上设置 :has_many :through 关联 Ruby on Rails

发布于 2024-09-26 03:43:18 字数 479 浏览 7 评论 0原文

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

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

正如您在评论文本中看到的,我已经提到了我需要的东西。

I have three models, each having the following associations:

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

As you can see in the commented text, I have mentioned what I need.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘦怹 2024-10-03 03:43:18

您只需创建访问它的方法

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

You just create the method to access it

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

Or, you can delegate to model1 the model3s method

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end
拧巴小姐 2024-10-03 03:43:18

为什么不尝试:

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

这将使活动记录通过 model1_id 连接 model2 和 model3,而将 model1 完全排除在外,并且应该更高效。

Why not try:

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

This will have active record join model2 and model3 by model1_id leaving model1 completely out of it and should be more efficient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文