查找对象集合对给定属性是否具有相同的值

时间:2022-12-12 21:28:58

I have two related models : Invoice and Currency.

我有两个相关的模型:发票和货币。

Invoice belongs_to Currency and Currency has_many Invoices

发票归属货币和货币有许多发票

I have a table which displays the list of every invoices and I am able to filter them by currency. An invoice also has a pricefield and I have a method which calculates the total price of invoices I display.

我有一个表格,显示了每个发票的清单,我可以按货币进行筛选。发票也有一个pricefield,我有一个计算我所显示的发票总价格的方法。

My problem is that I want to display the total price if and only if every invoices have the same currency.

我的问题是,如果且仅当每个发票都有相同的货币时,我想显示总价格。

I am pretty sure there is a simple way to achieve this but I can't find it out.

我很确定有一个简单的方法来实现这个,但是我找不到。

Any help would be greatly appreciated.

如有任何帮助,我们将不胜感激。

2 个解决方案

#1


4  

in fact, there are many ways to achieve that, e.g, you can check if all of them have the same currency this way:

事实上,有很多方法可以做到这一点,e。g,你可以检查他们是否都有相同的货币:

invoices.reject {|inv| inv.currency_id == invoices[0].currency_id}.empty?

or

invoices.map {|inv| inv.currency_id}.uniq.length == 1

#2


2  

The most straight forward way to ask if everything in a collection is the same is to ask if all elements equal the first one:

问集合中的所有元素是否相同的最直接的方法是问所有元素是否都等于第一个元素:

invoices.all?{ |inv| inv.currency_id == invoices.first.currency_id }

If you do this thing a lot, one might consider extended Enumerable with a convenience method:

如果你经常这样做,你可以考虑用一种方便的方法扩展可枚举:

module Enumerable
  def all_same?
    v = first
    all? {|e| e == v}
  end
end

invoices.map(&:currency_id).all_same?

#1


4  

in fact, there are many ways to achieve that, e.g, you can check if all of them have the same currency this way:

事实上,有很多方法可以做到这一点,e。g,你可以检查他们是否都有相同的货币:

invoices.reject {|inv| inv.currency_id == invoices[0].currency_id}.empty?

or

invoices.map {|inv| inv.currency_id}.uniq.length == 1

#2


2  

The most straight forward way to ask if everything in a collection is the same is to ask if all elements equal the first one:

问集合中的所有元素是否相同的最直接的方法是问所有元素是否都等于第一个元素:

invoices.all?{ |inv| inv.currency_id == invoices.first.currency_id }

If you do this thing a lot, one might consider extended Enumerable with a convenience method:

如果你经常这样做,你可以考虑用一种方便的方法扩展可枚举:

module Enumerable
  def all_same?
    v = first
    all? {|e| e == v}
  end
end

invoices.map(&:currency_id).all_same?