0

我有这样的模型结构:

class User < ActiveRecord::Base
  has_many :groups, :through => :user_groups
  has_many :orders
  has_many :user_groups
end

-

class UserGroup < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

-

class Group < ActiveRecord::Base
  has_many :user_groups
  has_many :users, :through => :user_groups
end

在模型组中,我有字段标记。我如何通过它的 user_groups 为每个用户获取组的标记字段?

我这样尝试:

user.user_groups.each do |u|
  summ += u.groups.markup
end

当然它不起作用......但是如何从第三个模型中获取数据?

4

2 回答 2

2

user.groups.map(&:markup).sum应该做得很好

编辑:

I used #flat_map because I was thinking that it was a nested array. But has_many :through would combine it into a single result list, so #map will be fine

EDIT2:

In discussion with @VladisAzamaris, it was pointed out that the markup column is a float, so sum is more appropriate than join

于 2013-01-13T21:00:39.683 回答
1

首先,不妨在这里利用这has_many :through一点:

user.groups # => all the groups to which this user belongs

像这样的东西如何获得标记?这会将它们全部放在一个列表中,除非您确实确实希望它们全部放在一个大字符串中,在这种情况下您将加入它们。

user.groups.map(&:markup)

此外,如果模型上没有任何其他字段UserGroup,请考虑一种has_and_belongs_to_many关系,在这种关系中,Rails 会为您处理该粘合UserGroup模型,而不是让您声明它。

于 2013-01-13T21:00:32.430 回答