0
我有一個表單,允許用戶通過在逗號分隔的列表中添加電子郵件來邀請多個人。在我的「參與者」模型中,我打電話來驗證輸入電子郵件的唯一性(範圍由「project_id」)。在模型驗證中,它給出瞭解釋錯誤(消息)的地方,但是如果驗證失敗,我不能在我的表單上顯示該錯誤。
如果用戶輸入已經添加的人員的電子郵件,如何獲取錯誤消息進行呈現?模型驗證消息Rails 4表單錯誤沒有顯示
participant.rb
class Participant < ActiveRecord::Base
validates :email, uniqueness: {case_sensitive: false, scope: :project_id, message: "Looks like you\'ve already added this person."}
end
participant_controller.rb
def new_participant
@new_participants = Participant.new
@participants = Participant.where(project_id: @project.id).includes(:user)
@template = Template.find(@project.template_id)
@address = Address.where(project_id: @project.id).first
@food = ProjectRestriction.where(project_id: @project.id)
end
def add_participant
@added_by = User.find(current_user.id)
@new_participants = params[:new_participants][:email].split(/,\s*/)
@new_participants.each do |t|
newpart = Participant.new(:email => t, :project_id => @project.id, :level => 4,
:participant_cat_id => 2, :last_updated_by => current_user.id, :added_by => current_user.id, :status => 'unseen')
respond_to do |format|
if newpart.save
ProjectMailer.notify_recipient(newpart, @project, @added_by, @participant_invite).deliver_later
self.response_body = nil
redirect_to participants_path(p: @project.id, w: 'recipient')
else
format.html { redirect_to new_participant_path(p: @project.id)}
format.json { render json: @new_participants.errors, status: :unprocessable_entity }
end
end
end
end
形式
<%= form_for :new_participants, url: add_participant_path(:p => @project.id), html: { :multipart => true, :class=> "form-horizontal", id: "basicForm" } do |f| %>
<% if @new_participants.errors.any? %>
<h2>OOPS!</h2>
<ul>
<% @new_participants.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul></div>
<% end %>
<div class="form-group ">
<label class="form-label dk-aqua"> Email: <span class="asterisk">*</span></label>
<%= f.text_field :email, :autofocus => true, :required => true, :maxlength => 55, :placeholder => 'Email(s)', :class => 'form-control' %>
</div>
<%= f.submit 'INVITE', :class => 'btn btn-aqua btn-lg btn-block',
:style => 'margin-bottom:-5px' %>
<% end %>