2013-01-13 36 views
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 

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

我试试这样:

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

当然这是不工作...但是,如何来从第三模型数据?

回答

2

user.groups.map(&:markup).sum应该这样做就好了

编辑:

我用#flat_map,因为我在想,这是一个嵌套数组。但是的has_many:通过将其合并成一个单一的结果列表,所以#map将被罚款

EDIT2:

与@VladisAzamaris讨论中,有人指出,markup列是一个浮点数,所以sum是比join更合适

+0

我新来的铁轨...如何把它写在循环summ标记? –

+0

flat_map + join进行求和。如果您执行'sum = user.groups.flat_map(&:markup).join('')',那么sum将保存组合标记。我建议先做一些Ruby教程,如果这不是很明显 –

+0

不!如果我这样做,我只是在视图中看到我的值的数组,但不是summ –

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模型为你而不是你声明它。