简体   繁体   中英

Error messages not showing up on page

I'm making validations for my rails app, and the validation is working. However, it still displays the success message and it does not display the error message. I'm sure I am missing something simple! Here is my code.

def create
  @message = Message.create(message_params)
  if @message.send_at.blank?
    Person.in_groups(message_params[:group_ids]).each do |person|
      person.delay.send_message(@message.body)
      flash[:success] = "Messages on their way!"
    end
  else
    Person.in_groups(message_params[:group_ids]).each do |person|
      person.delay(run_at: @message.send_at).send_message(@message.body)
      flash[:success] = "Messages on their way!"
    end
  end
  redirect_to root_path
end

hers is my view

<% if @message.errors.any? %>
  <ul>
    <% @message.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
<% end %>

The way I normally go about it is:

def create
  @message = Message.build(message_params)
  if @message.save
    run_at_time = @message.send_at.present? ? @message.send_at : Time.zone.now
    people = Person.in_groups(message_params[:group_ids])
    if people.any?
      people.each do |person|
        person.delay(run_at: run_at_time).send_message(@message.body)
      end
      flash[:success] = 'Messages on their way!'
      redirect_to_root_path
    else
      flash[:danger] = 'No people to send messages to.'
      render 'new'
    end
  else
    flash[:danger] = 'There was an error with message creation.'
    render 'new'
  end
end

That way @message.save will return true or false, and depending on whether it succeeds through validations you can have it render the form, or redirect to root.

I also added a bit of code to show an error if there are not any people in the groups to send messages to. Not directly related to question, but I noticed the possibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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