繁体   English   中英

通过父公开has_many-> has_many的关联?

[英]Exposing associations of a has_many -> has_many through the parent?

如果用户有很多东西,并且一个东西有很多统计信息,那么似乎只有一种Rails-y方法可以通过用户公开统计信息。

class User < ActiveRecord::Base
  has_many :things do
    def stats
      Stat.where(thing_id: proxy_association.owner.things_id)
    end
  end
end

class Thing < ActiveRecord::Base
  belongs_to :user
  has_many :stats
end

class Stat < ActiveRecord::Base
  belongs_to :thing
  has_one :user, through: :thing
end

User.first.things.stats == Stat.where(thing_id: User.first.thing_ids)

我正在尝试确定是否还有其他选择...我团队中的某些人抱怨这不自然。 我觉得这是您可以设计的关系中最自然的表达。

有谁有更好的建议? 我会说,我尝试了实例方法,但它们闻起来不正确。

我可能在User类中使用has_many:stats,:through =>:things。

查看以下内容: http : //guides.rubyonrails.org/association_basics.html#the-has_many-through-association

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM