简体   繁体   English

您如何在Rails中创建一系列电子邮件?

[英]How do you create an array of emails in rails?

I am trying to create an array of emails from my user model, with a helper method to access them. 我试图通过我的用户模型创建一系列电子邮件,并使用一种辅助方法来访问它们。 I will then load this array into a drop down selector. 然后,我将该数组加载到下拉选择器中。 I am new to rails, and the MVC framework is new to me also. 我是Rails的新手,MVC框架也是我的新手。

In my application_helper.rb 在我的application_helper.rb中

  def create_user_selector_array
    @user = User.select(:email).distinct
  end

In my _form.html.erb partial 在我的_form.html.erb部分

<%= f.select(:associate, @user.map { |value| [ value, value ] }) %>
<%= @user %> 

What appears to be happing when I launch this site, is that my selector contains this: 当我启动此站点时,似乎在选择的是我的选择器包含以下内容:

#<User:>(Characters)

And when I pull just the array it prints this: 当我只拉数组时,它输出:

ActiveRecord::Relation::ActiveRecord_Relation_User:0x007fb28894d508>

I feel close, but I'm not entirely sure what I'm doing wrong here. 我感觉很亲密,但我不确定自己在做什么错。

In Rails 3.2 and newer, you can use pluck : 在Rails 3.2和更高版本中,可以使用pluck

User.pluck(:email)
# => ["foo@example.com", "bar@example.com"]

Otherwise, your solution just needed a map : 否则,您的解决方案只需要一张map

@user = User.select(:email).distinct.map(&:email)

Using select just determines what fields get returned, however you still get an array of ActiveRecord objects, not strings like you were expecting. 使用select只能确定返回哪些字段,但是您仍然会得到一个ActiveRecord对象数组,而不是您期望的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM