了解Rails渲染来自控制器的错误

时间:2019-04-08 14:39:12

标签: ruby-on-rails ruby erb

我仍然对Rails还是陌生的,并且在理解如何有条件地呈现页面的某些部分时遇到了麻烦。我在index.html.erb中有一个按钮以及另一个局部渲染的视图:

<%= @facade.processing_button %>
<%= render 'snap', app: @facade.app %>

其定义如下:

link_to processing_path(@app.id),
  method: :post, action: :processing,
  class: 'btn btn-danger' do
    concat([
      image_tag('blah', class: 'check_icon'),
      content_tag(:span, 'Processing')
    ].join(' ').html_safe)
  end

此按钮调用控制器方法:

def processing
  if service.upload
    # render success bar?
  else
    # render error bar?
  end
end

我想渲染以下图片。在snap部分中,一个部分通常如下所示:

default

单击按钮后,如果操作成功,则要呈现以下绿色成功栏:

enter image description here

我不清楚如何实现这一目标。我应该利用某种形式的JS / CoffeeScript吗?我是否应该将条形图默认添加为部分条形,并在操作完成后简单地用JS显示它们?

3 个答案:

答案 0 :(得分:2)

  1. link_to processing_path(@app.id), method: :post, action: :processing同时使用_path:action参数是没有意义的。仅使用其中之一
  2. 您需要确定按钮是在执行“传统”请求还是AJAX请求
  3. 如果是传统请求,则可以使用控制器变量@success = ...,然后在视图中检查以下变量:<% if @success %>
  4. 在AJAX请求的情况下,事情会变得有些复杂。但是,Rails支持“成功”和“失败” AJAX响应。看一下https://guides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers。通常,您会根据服务器的响应显示/隐藏页面上的某些元素

答案 1 :(得分:0)

您的布局中将需要类似的内容

  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, class: "alert alert-info" %>
  <% end %>

然后在您的控制器上

def processing
  if service.upload
    flash[:notice] = "Success"
  else
    flash[:notice] = "Error"
  end
end

看看这个:rails 4 -- flash notice

答案 2 :(得分:0)

请参阅文档:https://coderwall.com/p/jzofog/ruby-on-rails-flash-messages-with-bootstrap

步骤1:在layouts / application.html.erb文件中添加Flash代码

<% flash.each do |key, value| %>
    <div class="<%= flash_class(key) %>">
        <%= value %>
  </div>
<% end %>

步骤2:只需使用以下内容快速扩展application_helper.rb

def flash_class(level)
    case level
        when :notice then "alert alert-info"  
        when :success then "alert alert-success"
        when :error then "alert alert-error"
        when :alert then "alert alert-error"
     end
end

# sometimes it will not work then wrap it with single quotes. for example:  
  when 'notice' then "alert alert-success"

第3步:在controller.erb中添加以下内容

 def processing
   if service.upload
      flash[:success] = "Processing complete!"
   else
      flash[:error] = "Something went wrong!"
   end
 end

希望它会起作用:)