【发布时间】:2016-08-03 07:52:39
【问题描述】:
我正在尝试在 RoR 中创建一个系统来发送电子邮件,我希望用户能够通过表单上的复选框选择多个电子邮件地址,然后系统循环通过每个选定的复选框发送一个给每个人发电子邮件。此时,用户可以在表单上选择多个电子邮件地址,系统将它们连接在一起,以便将一封电子邮件发送给多个收件人,例如用户选择电子邮件地址“1@a.com”和“2@b.com”,系统会向“1@a.com;2@b.com”发送电子邮件。
我通过视图做到了这一点:
<%= form_for(@email) do |f| %>
<% if @email.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:</h2>
<ul>
<% @email.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :from_name %><br>
<% if @user.present? %>
<%= f.select :from_name, [@user.firstname + " " + @user.surname, @user.organisation] %>
<% end %>
</p>
<p>
<%= f.label :From_Email_Address %><br>
<%= f.collection_select :account_id, Account.where(user_id: session[:user_id]),
:id,:email %>
</p>
<p>
<%= f.label :to %><br>
<%= f.collection_check_boxes(:to, @contacts, :email, :email) %>
</p>
<p>
<%= f.label :cc %><br>
<%= f.text_field :cc %>
</p>
<p>
<%= f.label :bcc %><br>
<%= f.text_field :bcc %>
</p>
<p>
<%= f.label :subject %><br>
<%= f.text_field :subject %>
</p>
<p>
<%= f.label :message %><br>
<%= f.text_field :message %>
</p>
<div class="actions">
<%= f.submit %>
</div>
<%= f.collection_check_boxes(:to, @contacts, :email, :email) %> 行显示保存在联系人数据库表中的每个电子邮件地址的复选框。
然后通过emails_controller,它具有以下代码:
class EmailsController < ApplicationController
before_action :set_email, only: [:show, :edit, :update, :destroy]
def index
# Only show the email accounts for the user logged in
@emails = Email.where(user_id: session[:user_id])
end
def show
end
def new
@user = User.find(session[:user_id])
@contacts = Contact.where(user_id: session[:user_id])
@email = Email.new
end
def edit
@user = User.find(session[:user_id])
@contacts = Contact.where(user_id: session[:user_id])
end
def create
@email = Email.new(email_params)
@email.user_id = session[:user_id]
@user = session[:user_id]
if @email.save
UserEmails.send_email(@email).deliver_now
redirect_to @email, notice: 'Email was successfully created.'
else
redirect 'new'
end
end
def update
if @email.update(email_params)
redirect_to @email, notice: 'Email was successfully updated.'
else
redirect 'edit'
end
end
def destroy
@email.destroy
redirect_to emails_url, notice: 'Email was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_email
@email = Email.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def email_params
res = params.require(:email).permit(:account_id, :cc, :bcc, :subject, :message, :from_name, to: [])
res[:to] = res[:to].join('; ')
res
end
end
使用email_params 代码将选择的电子邮件地址与“;”一起连接每个人之间。
正如您在上面的 create 方法中看到的,代码 UserEmails.send_email(@email).deliver_now 在电子邮件保存后运行 - 此代码将电子邮件发送出去。
那么,我的问题是,是否有人可以帮助我更改代码,以便将一封电子邮件发送到表单上选择的每个电子邮件地址?
下面是我的带有复选框的表单的样子。
【问题讨论】:
标签: ruby-on-rails ruby email ruby-on-rails-4 checkbox