Ada*_*dam 3 ruby forms ruby-on-rails duplicates ruby-on-rails-3
我正在尝试做一些有点共同的事情 - 在使用时在表单上的列表中生成一系列唯一项collection_select.用户has many付款和付款belongs_to用户.我正在使用Devise,所以知道了current_user.
我可以使用以下代码在视图中成功生成包含重复的电子邮件列表:
<%= form_for(@payment) do |f| %>
.
.
.
<%= f.collection_select :email, current_user.payment, :email, :email, {:include_blank => "Please select"} %>
Run Code Online (Sandbox Code Playgroud)
但是,我无法获得相同的电子邮件列表,以消除重复.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"} %>
Run Code Online (Sandbox Code Playgroud)
我收到错误消息undefined方法'email'为"test@example.com":字符串.任何人都可以帮助我理解(1)为什么我使用的代码不正确,以及(2)代码中的更改?
非常感谢您提供的任何帮助!
要理解错误(问题1):
collection_select需要一组对象,并将值和标签方法发送给这些对象.
在collect或之后pluck,您有一个字符串数组,因此将value或label方法:mail发送到此字符串会产生错误.
要解决此问题,请优化返回的关系current_user.payments:
<%= f.collection_select :email, current_user.payment.select(:email).uniq, :email, :email, {:include_blank => "Please select"} %>
Run Code Online (Sandbox Code Playgroud)
uniq作为关系的一部分,仅适用于Rails 3.2或更高版本.使用早期的Rails版本,它是:
<%= f.collection_select :email, current_user.payment.select('distinct email'), :email, :email, {:include_blank => "Please select"} %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1391 次 |
| 最近记录: |