簡體   English   中英

在belongs_to關聯上設置:has_many:through關聯Ruby on Rails

[英]Setting a :has_many :through association on a belongs_to association 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

為什么不嘗試:

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完全排除在模型之外,並且應該更有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM