Ruby on Rails 3:如何访问 has_many 查询中每条记录的属性
我不确定如何在标题中表达它,但我正在尝试执行以下操作。我有两个具有以下关系的模型:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会这样做:
I'd do:
应该可以解决问题。
should do the trick.
你可以按照那些人说的去做。在它们的末尾添加
.uniq
并最终得到正确的解决方案,或者;让我用 ActiveRecord 的乐趣引导您误入歧途(可能会失败,因为我无法测试它是否在这里有效)。但您将能够按照您想要的方式运行
campaign.points.locales
。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.