简体   繁体   English

错误消息未显示在页面上

[英]Error messages not showing up on page

I'm making validations for my rails app, and the validation is working. 我正在为我的Rails应用程序进行验证,并且验证工作正常。 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. 这样,@ message.save将返回true或false,并且取决于它是否通过验证成功,您可以使其呈现表单或重定向到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. 与问题没有直接关系,但我注意到了可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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