为什么uniq!方法有效但排序!不在 Rails 的这个数组上?

发布于 2024-09-28 02:00:09 字数 752 浏览 0 评论 0原文

这是我创建数组的方法:

@companies_with_email = Company.contact_emails_date_sent_gt(@monday).
                                contact_emails_date_sent_lt(@friday).
                                find(:all, :select => "distinct companies.* ") || []

@companies_with_call = Company.contact_calls_date_sent_gt(@monday).
                                contact_calls_date_sent_lt(@friday).
                                find(:all, :select => "distinct companies.* ") || []

@companies_with_activity = @companies_with_email + @companies_with_call
@companies_with_activity.uniq!

但是,我希望它按字母顺序排列,所以我尝试添加 .sort!我收到一条错误消息 <=>;方法不存在。

undefined method `<=>' for #<Company:0x9d506a8>

Here is how I created an array:

@companies_with_email = Company.contact_emails_date_sent_gt(@monday).
                                contact_emails_date_sent_lt(@friday).
                                find(:all, :select => "distinct companies.* ") || []

@companies_with_call = Company.contact_calls_date_sent_gt(@monday).
                                contact_calls_date_sent_lt(@friday).
                                find(:all, :select => "distinct companies.* ") || []

@companies_with_activity = @companies_with_email + @companies_with_call
@companies_with_activity.uniq!

However, I want it to be in alphabetical order, so I tried to add .sort! and I got an error saying <=> method doesn't exist.

undefined method `<=>' for #<Company:0x9d506a8>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

池木 2024-10-05 02:00:09

排序公司并不“有效”。该错误消息意味着无法仅比较(在本例中使用比较运算符 <=>)两家公司,因为它不知道您要比较什么:数据库中的 ID、名称、Ruby 内存中的 ID 等。

不过,您可以自己定义排序行为:

@companies_with_activity.sort! { |a,b| a.name <=> b.name }

Sorting companies doesn't "just work". What that error message means is that there is no way to just compare (use the comparison operator <=>, in this case) two companies, since it doesn't know what you would compare: ID in database, name, ID in Ruby memory, etc.

You can define sorting behavior yourself, though:

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