0

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

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

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

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

4

3 回答 3

1

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

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

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

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

于 2012-11-30T05:26:46.057 回答
0

through选项:

has_many :programs, through: :computers

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

于 2012-11-30T05:24:18.390 回答
0

你可以这样做:

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
于 2012-11-30T05:24:37.293 回答