ruby-on-rails - 使用 collection_select 时如何删除重复条目以获得唯一元素?出现错误 - 知道为什么吗?

标签 ruby-on-rails ruby ruby-on-rails-3 forms duplicates

我正在尝试做一些比较常见的事情 - 在使用 collection_select 时在表单的列表中生成一组独特的项目。一个用户有很多支付,一个支付belongs_to用户。我正在使用 Devise,所以知道 current_user

我可以使用以下代码在 View 中成功生成具有重复的电子邮件列表:

<%= form_for(@payment) do |f| %>
.
.
.
   <%= f.collection_select :email, current_user.payment, :email, :email, {:include_blank => "Please select"} %>

但是,我无法获得消除重复项的相同电子邮件列表。这个问题已在 Stackoverflow 上被问过几次,但我没有成功实现其他解决方案。我试过(没有运气):

<%= f.collection_select :email, current_user.payment.collect(&:email).uniq, :email, :email, {:include_blank => "Please select"} %>
<%= f.collection_select :email, current_user.payment.pluck(:email).uniq, :email, :email, {:include_blank => "Please select"} %>

我收到错误消息 undefined method 'email' for "test@example.com":String。任何人都可以帮助我理解(1)为什么我使用的代码不正确,以及(2)对代码进行哪些更改?

非常感谢您提供的任何帮助!

最佳答案

要理解错误(问题 1): collection_select 需要一个对象集合,并将值和标签方法发送到这些对象。

collectpluck 之后,您有一个字符串数组,因此发送值或标签方法:mail 这个字符串给出了你的错误。

要解决这个问题,请改进 current_user.payments 返回的关系:

<%= f.collection_select :email, current_user.payment.select(:email).uniq, :email, :email, {:include_blank => "Please select"} %>

uniq 作为关系的一部分,仅适用于 Rails 3.2 或更高版本。对于早期的 Rails 版本,它是:

<%= f.collection_select :email, current_user.payment.select('distinct email'), :email, :email, {:include_blank => "Please select"} %>

关于ruby-on-rails - 使用 collection_select 时如何删除重复条目以获得唯一元素?出现错误 - 知道为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760237/

相关文章:

javascript - Rails .js.erb 模板不再适用于 Webpack

ruby-on-rails - Rails 3 真实性 token

sql - 具有 has_many 关系的订单

ruby - Rails 3 + Devise + Rspec - Controller 测试中的未定义方法错误

ruby-on-rails - Ruby on Rails - 定义模型或表的复数名称

html - 在 Rails 邮件程序中分别编写 html 和 Css 的最佳方式。并在发送邮件时将两者结合起来

ruby - 我应该如何在开发过程中试用我的 gem?

ruby - 为 nil :NilClass"in Ruby for optional associations? 处理每个 "undefined method ` 的优雅方式

php - 在 PHP 函数签名中模拟 Ruby "splat"运算符的最佳方法 [方法重载]

ruby-on-rails - Rails "has_many"与 NULL 外键的关联