在rails中,如何在与其他模型连接后获取模型的所有参数,获取 ActiveRecord::Relation ,其中 count 的方法返回一个数字
假设我有以下模型:
class Item
# (name, price, location, quantity)
has_many :purchases
end
class Purchase
has_many :items
belongs_to :person
end
class Person
# (name, age)
has_many :purchases
end
我需要查找名为“bob”的人购买的名为“cd”的所有唯一商品
然后在我看来我需要:
@items
来包含唯一记录@items.count
返回一个数字循环时访问每个项目的所有属性:
<% @items.each do |i| %> <%= "#{i.name}, #{i.location}, #{i.quantity}" %> <%结束%>
@items 成为 ActiveRecord::Relation(以便我可以分页)
到目前为止我的查询看起来像这样:
@items = Item.joins(:purchase => :person).where('person.name' => 'bob')
像这样保留@items有包含重复项目的问题
我尝试过:
1)@items.uniq
删除重复项但返回一个数组,我需要一个 ActiveRecord::Relation
2) @items.select('distinct(items.name)')
删除重复项,但返回一个仅包含 item.name 的关系,我需要所有属性
3) @items.group('items.name')
删除重复项并返回一个关系,但 count 方法返回 OrderedHash 而不是数字 是的,我可以对键进行计数,但对于在关系上调用 count 方法时返回数字的其他关系,我有相同的看法。
我真的不知道还能尝试什么,有什么建议吗?
Lets suppose I have the following models:
class Item
# (name, price, location, quantity)
has_many :purchases
end
class Purchase
has_many :items
belongs_to :person
end
class Person
# (name, age)
has_many :purchases
end
I need to Find all the unique items with name "cd" bought by person named "bob"
Then in my view I need:
@items
to contain unique records@items.count
to return a numberaccess all the attributes of each item when looping:
<% @items.each do |i| %> <%= "#{i.name}, #{i.locatiton}, #{i.quantity}" %> <% end %>
@items to be an ActiveRecord::Relation (so I can paginate)
My query until now looks something like this:
@items = Item.joins(:purchase => :person).where('person.name' => 'bob')
leaving @items like it is has the problem that contains duplicate items
What I've tried:
1) @items.uniq
removes the duplicates but returns an array and I need an ActiveRecord::Relation
2) @items.select('distinct(items.name)')
removes the duplicates but returns a relation containing only the item.name and I need all the attributes
3) @items.group('items.name')
removes the duplicates and returns a relation but the count method returns an OrderedHash not a number
yes I can count the keys but I have the same views for other relations that return a number when calling the count method on the relation.
I really don't know what else to try, any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你可以这样做:
并使用 Items 中你需要的东西。你尝试过吗?
I guess you can do:
And use what you need from Items. Did you tried it?