了解Rails从控制器渲染错误

问题描述 投票:0回答:3

我仍然是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 partial中,一个部分通常如下所示:

default

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

enter image description here

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

ruby-on-rails ruby erb
3个回答
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。通常,您将显示/隐藏页面上的某些元素,具体取决于服务器响应

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


0
投票

见Doc: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

希望它会工作:)

© www.soinside.com 2019 - 2024. All rights reserved.