gpt4 book ai didi

ruby-on-rails - 设置一个 :has_many :through association on a belongs_to association Ruby on Rails

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:03 28 4
gpt4 key购买 nike

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

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 方法委托(delegate)给 model1

class Model2 < ActiveRecord::Base
belongs_to :model1

delegate :model3s, :to => :model1

end

关于ruby-on-rails - 设置一个 :has_many :through association on a belongs_to association Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3864143/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com