I have a form which allows a user to invite multiple people via adding emails in a comma separated list. In my "Participant" model, I have a call to validate the uniqueness of the email entered (scoped by "project_id"). In the model validation, it gives a place to explain the error (message), but I can't get that error to show up on my form if the validation fails.
If a user enters the email of a person that has already been added, how can I get the errors message to render?
participant.rb
Application.ScreenUpdating = False
participant_controller.rb
class Participant < ActiveRecord::Base
validates :email, uniqueness: {case_sensitive: false, scope: :project_id, message: "Looks like you\'ve already added this person."}
end
form
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
答案 0 :(得分:2)
您的主要问题是:
@new_participants
中存储在内存中的对象实际上并未保存。@new_participants
视为单一资源。在命名路线,变量和操作时要注意多元化。
def add_participants
@added_by = User.find(current_user.id)
@new_participants = params[:new_participants][:email].split(/,\s*/)
@new_participants.map do |email|
newpart = Participant.new(
:email => email,
:project_id => @project.id,
:level => 4,
:participant_cat_id => 2,
:last_updated_by => current_user.id,
:added_by => current_user.id,
:status => 'unseen'
)
if newpart.save
ProjectMailer.notify_recipient(newpart, @project, @added_by, @participant_invite ).deliver_later
end
new_part
end
@invalid = @new_participants.reject(&:valid?)
if @invalid.any?
respond_to do |format|
format.html { redirect_to new_participant_path(p: @project.id)}
format.json { render json: @new_participants.map(&:errors), status: :unprocessable_entity }
end
else
respond_to do |format|
redirect_to participants_path(p: @project.id, w: 'recipient')
end
end
end
<ul>
<% @new_participants.each |p| %>
<% p.errors.messages.each do |msg| %>
<li><%= msg %></li>
<% end if p.errors.any? %>
<% end %>
</ul>