我的问题是如果我有3个表单和一个提交按钮该怎么办。
我想创建一个表单,向每个收件人发送电子邮件,然后在免费注册优惠券表中创建新记录。
我需要确认这张表格的电子邮件。
模型免费注册优惠券:收件人电子邮件、令牌、发件人ID
现在我有这个:

class FreeRegistrationCouponsController < ApplicationController
  def send_invitations
    emails = [params[:recipient_email_1], params[:recipient_email_2], params[:recipient_email_3]]
    emails.reject!{ |e| e.eql?("") }

    if emails.present?
      emails.each do |e|
        FreeRegistrationCoupon.create(:recipient_email => e, :sender_id => current_user.id)
        #MAILER
      end
      redirect_to root_path, :notice => "You just send #{emails.size} invitations!"
    else
      redirect_to(:back)
    end
  end
end


class FreeRegistrationCoupon < ActiveRecord::Base
  before_save :generate_token

  attr_accessor :recipient_email, :sender_id
  validates :recipient_email, :presence => true, :email => true

  def generate_token
    self.token = SecureRandom.hex
  end
end

这是其他控制器CarsControl中的表格,请确认:
<%= form_tag :controller => 'free_registration_coupons', :action => "send_invitations" do %>
  <!-- errors -->
  <%= label_tag :recipient_email_1 %>
  <%= text_field_tag :recipient_email_1 %>
  <%= label_tag :recipient_email_2 %>
  <%= text_field_tag :recipient_email_2 %>
  <%= label_tag :recipient_email_3 %>
  <%= text_field_tag :recipient_email_3 %>
  <%= submit_tag %>
<% end %>

最佳答案

我认为您应该使用以下定义表单:

<%= form_tag :controller => 'free_registration_coupons', :action => "send_invitations" do %>
  <%= @error_message %>
  <%= label_tag "recipient_email[1]" %>
  <%= text_field_tag "recipient_email[1]" %>
  <%= label_tag "recipient_email[2]" %>
  <%= text_field_tag "recipient_email[2]" %>
  <%= label_tag "recipient_email[3]" %>
  <%= text_field_tag "recipient_email[3]" %>
  <%= submit_tag %>
<% end %>

这样可以更容易地处理控制器上的所有电子邮件地址,并且您可以跟踪这些错误以在以后显示它们:
class FreeRegistrationCouponsController < ApplicationController
  def send_invitations
    emails = params[:recipient_email]
    emails.reject!{ |param, value| value.eql?("") }
    errors = []
    if emails.any?
      emails.each do |param, value|
        validation_result = FreeRegistrationCoupon.save(:recipient_email => value, :sender_id => current_user.id)
        #MAILER
      end
      redirect_to root_path, :notice => "You just send #{emails.size} invitations!"
    else
      @error_message = "You have to include, at least, one e-mail address!"
      render :name_of_the_action_that_called_send_invitations
    end
  end
end

我没有测试这个代码。希望有帮助!

10-01 07:16
查看更多