我有一个模型Item
,其中has_many Votes
。投票只能属于一个项目。如果我有一个投票数组@votes = Vote.where(ip: "1")
,我怎样才能在@votes
中获得与投票相关联的项目数组?
例如,如果@votes.first.item.name => "Item1"
,则“Item1”应该是新数组中的第一个项目。
模型
class Item < ActiveRecord::Base
has_many :votes
end
class Vote < ActiveRecord::Base
belongs_to :item
end
答案 0 :(得分:1)
考虑到您使用的是ActiveRecord,我建议您使用它来直接获取您的列表:
@items = Item.joins(:votes).where(votes: {ip: "1"})
通过这种方式,Rails构建一个查询来获取您正在查找的项目列表,而无需构建操作数组的列表。