2016-03-24 43 views
0

我正在對我的Rails應用程序進行驗證,驗證正在工作。但是,它仍顯示成功消息,並且不顯示錯誤消息。我相信我錯過了一些簡單的東西!這是我的代碼。錯誤消息沒有顯示在頁面上

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 

她是我的看法

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

...什麼錯誤信息?您發佈的代碼中沒有任何內容。發佈你的看法,如果你只是在驗證錯誤後,可能是看看的地方。 – Matt

+0

您的創建方法會重定向創建是否成功。重定向時,會丟失內存中的對象。 @ MTarantini的建議通過渲染來處理保存失敗,而不會丟失內存。 – Matt

回答

0

我通常去了解它的方式是:

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 

這樣@ message.save將返回true或false,並根據是否它通過驗證成功,您可以讓它呈現表單或重定向到根。

如果組中沒有任何人發送消息,我還添加了一些代碼以顯示錯誤。與問題沒有直接關係,但我注意到了可能性。

+0

這個工程,但你可以告訴我一種方式沒有你犯的錯誤字符串。我只想讓軌道錯誤消息失去作用。 – Cambass

+0

您在視圖中顯示錯誤的方式仍然有效,因爲@ message.errors會保留它們。我只是添加閃光燈,在頁面頂部(或顯示它們的任何位置)向用戶顯示一條消息,以便他們很快知道發生了錯誤,並且可以向下滾動以查看導致錯誤的原因。如果你不想要它們,你可以刪除flash [:危險]行,你的錯誤仍然會顯示在視圖中。 – MTarantini

相關問題