加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:13:02 所属栏目:百科 来源:网络整理
导读:我有三个模型,每个模型都有以下关联: class Model1 ActiveRecord::Base has_many :model2s has_many :model3sendclass Model2 ActiveRecord::Base belongs_to :model1 has_many :model3s,:through = :model1 # will this work? is there any way around thi
我有三个模型,每个模型都有以下关联:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读