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

发布于 2025-01-05 18:23:09 字数 1125 浏览 3 评论 0原文

假设我有以下模型:

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 number
  • access 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 技术交流群。

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

发布评论

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

评论(1

梦屿孤独相伴 2025-01-12 18:23:09

我想你可以这样做:

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

并使用 Items 中你需要的东西。你尝试过吗?

I guess you can do:

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

And use what you need from Items. Did you tried it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文