【问题标题】:Rails best practice for multiple associations多个关联的 Rails 最佳实践
【发布时间】:2012-11-30 05:12:16
【问题描述】:

我的程序中有三个模型,采用层次结构:

User (has_many :computers)
Computer (has_many :programs, belongs_to :user)
Programs (belongs_to :computer)

在程序中,我需要通过扩展查看用户拥有多少程序。通过User.computers.programs 很容易做到这一点。

也就是说,直接声明UsersPrograms 之间的has_many/belongs_to 关系是否有益?会有任何好处(性能或其他方面),还是只会增加代码的复杂性?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations polymorphism


    【解决方案1】:

    这在很大程度上取决于您是否预见到需要经常访问该关系。如果您可以不使用该特定查询,那么您最好只使用一个

    class User < ActiveRecord::Base
      has_many :computers
      has_many :programs, :through => :computers
    end
    

    并完成它。完成相同任务的代码更少,更易于阅读/维护。

    但是,如果您要通过大型数据集访问该关系,则可能会以节省昂贵的JOINs 的名义以您所描述的方式对数据进行一些非规范化处理。

    【讨论】:

    • 等等,我接受了这个,但我有点迷茫。其他类的外观如何?我是否必须说计算机“属于”一个程序?
    【解决方案2】:

    through 选项:

    has_many :programs, through: :computers
    

    您可以在此处阅读更多信息: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

    【讨论】:

      【解决方案3】:

      你可以这样做:

      class User < ActiveRecord::Base
        has_many :computers
        has_many :programs, :through => :computers
      end
      

      这样你就可以做到:

      user = User.first #find some user
      user.programs #get a list of programs from the user through the computers they own
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2014-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多