我正在尝试做一些比较常见的事情 - 在使用 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
需要一个对象集合,并将值和标签方法发送到这些对象。
在collect
或pluck
之后,您有一个字符串数组,因此发送值或标签方法: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/