Ruby on Rails 3:如何访问 has_many 查询中每条记录的属性

发布于 2024-12-07 09:06:23 字数 601 浏览 0 评论 0原文

我不确定如何在标题中表达它,但我正在尝试执行以下操作。我有两个具有以下关系的模型:

class Campaign < ActiveRecord::Base
   has_many :points
end

class Point < ActiveRecord::Base
   belongs_to :campaign
end

现在,点模型具有“区域设置”属性,我希望能够将特定活动的每个点的所有“区域设置”放入数组、集合或其他内容中不必做类似

locales = Array.new
campaign.points.each do |p|
   locales << p.locale
end

我正在考虑的类似campaign.points.locales的事情。有没有一些很好的 Rails 方法来执行此查询,或者我只需要迭代集合?

感谢您的任何帮助。

编辑: 另外,因为该关系实际上是“has_many through”关系,所以此方法不起作用,因为如果我尝试以这种简单的方式进行迭代,我会得到许多重复的语言环境。听起来应该是某种类型的连接,但我不确定。

I wasn't sure how to phrase it in the title, but what I'm trying to do the following. I have 2 models that have the following relationships:

class Campaign < ActiveRecord::Base
   has_many :points
end

class Point < ActiveRecord::Base
   belongs_to :campaign
end

Now, the Point model has a "locale" attribute and I want to be able to put all the "locales" of every point of a specific campaign into an array, or collection, or whatever without having to do something like

locales = Array.new
campaign.points.each do |p|
   locales << p.locale
end

I was thinking of something along the lines of campaign.points.locales. Is there some nice Rails way of doing this query, or do I just have to iterate over the collection?

Thanks for any help.

EDIT: Also because the relationship is actually a "has_many through" relationship, this method doesn't work, as I get many repeated locales if I try to iterate in that simple way. It sounds like it should be some type of join, but I'm not sure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

咿呀咿呀哟 2024-12-14 09:06:23

我会这样做:

campaign.points.map(&:locale)

I'd do:

campaign.points.map(&:locale)
拥醉 2024-12-14 09:06:23
campaign.points.map {|p| p.locale}

应该可以解决问题。

campaign.points.map {|p| p.locale}

should do the trick.

太阳男子 2024-12-14 09:06:23

你可以按照那些人说的去做。在它们的末尾添加 .uniq 并最终得到正确的解决方案,或者;

让我用 ActiveRecord 的乐趣引导您误入歧途(可能会失败,因为我无法测试它是否在这里有效)。但您将能够按照您想要的方式运行campaign.points.locales

class Campaign < ActiveRecord::Base
  has_many :points do
    def locales
      select('DISTINCT(locale)').map(&:locale)
    end
  end
end

You could do what those guys said. Put a .uniq at the end of them and end up with the correct solution, or;

let me lead you astray with ActiveRecord fun (and possibly failure, since I can't test to see if it works here). But you'll be able to run campaign.points.locales just like you wanted.

class Campaign < ActiveRecord::Base
  has_many :points do
    def locales
      select('DISTINCT(locale)').map(&:locale)
    end
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文