繁体   English   中英

在rails中,如何在与其他模型连接后获取模型的所有参数,获得ActiveRecord :: Relation,其中count的方法返回一个数字

[英]in rails, how can I get all parameters of a model after joining with other models, get an ActiveRecord::Relation which count's method returns a number

假设我有以下模型:

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.locatiton}, #{i.quantity}" %> <% end %> 
  • @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方法。

我真的不知道还能尝试什么,有什么建议吗?

我想你可以做到:

@items.select("DISTINCT(`items`.`name`), `items`.*")

并使用您需要的物品。 你试过了吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM