【问题标题】:Fetch data from third model in rails从 rails 中的第三个模型获取数据
【发布时间】:2013-01-13 20:56:24
【问题描述】:

我有这样的模型结构:

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

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

【问题讨论】:

    标签: ruby-on-rails model rails-activerecord


    【解决方案1】:

    user.groups.map(&amp;:markup).sum 应该没问题

    编辑:

    我使用#flat_map 是因为我认为它是一个嵌套数组。但是 has_many :through 会将它组合成一个结果列表,所以 #map 就可以了

    EDIT2:

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

    【讨论】:

    • flat_map + join 进行求和。如果您执行sum = user.groups.flat_map(&amp;:markup).join(''),则 sum 将保存组合标记。如果这不是很明显,我建议先做一些 Ruby 教程
    • 不!如果我这样做,我只会在视图数组中看到我的值,而不是 summ
    • 加入的作用和你之前的+=一样
    • 它不起作用...我称之为,但在视图中,对于获取的 20 和 4 值,我看到的不是 24,而是 204,如果我删除连接,我会看到 [20,4]!
    • 啊,抱歉,还以为是字符串。将join('') 替换为sum
    【解决方案2】:

    首先,不妨在这里利用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 模型,而不是让您声明它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      相关资源
      最近更新 更多