ruby-on-rails “redirect_to”和“notice”闪存消息中的Rails路由错误

zpjtge22  于 2022-11-26  发布在  Ruby
关注(0)|答案(1)|浏览(91)

我需要在点击按钮时显示通知/弹出窗口。类似的方法在应用程序的其他视图和控制器中也有效,但在这个导入按钮上,事情已经很久没有工作了。没有一个redirect_to在控制器中有效,而它们在其他控制器中的类似用法有效。
routes.rb

Rails.application.routes.draw do
  namespace :admin do
    get '', to: 'dashboard#index', as: 'root'
    # resourceful routes 
    resources :oauth_clients
    resources :tenants do
      resources :sites do
        #resources :production_shifts
        resources :units do
          resources :log_data_fields, only: [:import, :create, :index, :destroy, :download_csv] do 
            get :download_csv
            # collection route 
            collection do 
              post :import #post action 
            end
          end

log_data_fields_controller.rb

class Admin::LogDataFieldsController < Admin::BaseController
  require 'csv'

  # import request(this is gonna be a POST action)
  def import
    logger.debug("*****Testing the logger.*****")
    
    file = params[:log_data_field][:file]
    
    # return redirect_to [:admin, @tenant, @site, @unit], notice: "Only CSV please !!" unless file.content_type == "text/csv"  
    return redirect_to admin_tenant_site_unit_log_data_fields_url, notice: "Only CSV please !!" unless file.content_type == "text/csv"  
    
    file = File.open(file)
    csv = CSV.parse(file, headers: true) 
    # csv = CSV.parse(file, headers: true, col_sep: ";") 
    
    @unit = Unit.find_by_id(params[:unit_id])
    # p @unit.id 
    
    total_rows = CSV.read(file).count
    count = 1
    # binding.b

    csv.each do |row|
      tag_hash = {}
      tag_hash[:name] = row["Name"]
      tag_hash[:alias] = row["Alias"]
      tag_hash[:column_type] = row["Type"]
      tag_hash[:unit_id] = @unit.id
      tag_hash[:is_active] = row["Active"]
      # binding.b
      # p row
      logger.debug("+++++++++++Mapping++++++++++++++")
      @log_data_field = LogDataField.create(tag_hash)
      # binding.b
      if @log_data_field.save
        count += 1
        logger.debug("--------Saves--------")
        # return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), 
      else
        # return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), 
        # render :_importtags 
      end  
    end
    
    logger.debug("-------------Going down----------")
    
    if count == total_rows && count > 1
      logger.debug("-------------All succeeded----------")
      redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Success"}
      # flash.notice = "Success : Tags imported from CSV !"
    elsif total_rows == 0
      logger.debug("-------------All zero----------")
      flash.alert = "Import Failure : CSV cant be empty"
      render :action => 'index', :notice => "Import Failure : CSV cant be empty."
    else
      logger.debug("-------------Failed down----------")
      flash.alert = "Import Failure"
      render :action => 'index', :notice => "Import Failure"
    end

    redirect_to import_admin_tenant_site_unit_log_data_fields_url(@tenant, @site, @unit), notice:"Imported tags !"
  end

_importtags.html.haml

%p{:style => "color: green"}= notice

= form_with model:@log_data_field, url: import_admin_tenant_site_unit_log_data_fields_path, method: :post do |form|

    - if @log_data_field.errors.any?
        #error_explanation
            %h2= "#{pluralize(@log_data_field.errors.count, "error")} prohibited this log_data_field from being saved:"
            %ul
            - @log_data_field.errors.full_messages.each do |message|
                %li= message

    -# = link_to 'Download sample csv', [:admin, @tenant, @site, @unit, @log_data_field], method: :get

    = form.file_field :file, accept: ".csv"
    -# = form.file_field :file
    <br>
    <br>

    -#button.btn.primary{:type => "submit", data: { disable_with: "Please wait..."}}
    %button.btn.primary{:type => "submit"}
        = "Import"

评论是我试过的东西。
对不起,如果你觉得这个问题或它的结构非常不专业,但我是初学者,经常学习。我需要再次渲染视图后,点击Import按钮,以显示任何错误(如果可用)或成功从csv导入标记。还有一个问题,通知不可见或弹出和redirect_to不工作时,非csv文档是在表单中提交的,该表单也应该给予警告,但它没有出现。
我相信解决方案将是非常短的或一些错字或愚蠢的错误,在理解路径与网址路线。

***EDIT***按照@markets的建议,我把所有的redirect_to都改成了return,它们在中间使用,所以通知可以正常工作,但是它们只在刷新时出现。仍然不能在点击按钮时立即得到它们:

class Admin::LogDataFieldsController < Admin::BaseController
  before_action :set_tenant
  before_action :set_site
  before_action :set_unit

  require 'csv'

  # import request(this is gonna be a POST action)
  def import
    logger.debug("*****Testing the logger.*****")
    
    file = params[:log_data_field][:file]
    
    # return redirect_to [:admin, @tenant, @site, @unit], notice: "Only CSV please !!" unless file.content_type == "text/csv"  
    return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), notice: "Only CSV please !!" unless file.content_type == "text/csv"  

    file = File.open(file)
    csv = CSV.parse(file, headers: true) 
    # csv = CSV.parse(file, headers: true, col_sep: ";") 
    
    @unit = Unit.find_by_id(params[:unit_id])
    # p @unit.id 
    
    total_rows = CSV.read(file).count
    count = 1
    # binding.b

    csv.each do |row|
      tag_hash = {}
      tag_hash[:name] = row["Name"]
      tag_hash[:alias] = row["Alias"]
      tag_hash[:column_type] = row["Type"]
      tag_hash[:unit_id] = @unit.id
      tag_hash[:is_active] = row["Active"]
      # binding.b
      # p row
      logger.debug("+++++++++++Mapping++++++++++++++")
      @log_data_field = LogDataField.create(tag_hash)
      # binding.b
      if @log_data_field.save
        count += 1
        logger.debug("--------Saves--------")
        # return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), 
      # else
        # return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), 
        # render :_importtags 
      end  
    end
    
    logger.debug("-------------Going down----------")
    
    if count == total_rows && count > 1
      logger.debug("-------------All succeeded----------")
      return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Success : Tags imported from CSV !"}
    elsif total_rows == 0
      logger.debug("-------------All zero----------")
      return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Import Failure : CSV cant be empty"}
    else
      logger.debug("-------------Failed down----------")
      return redirect_to admin_tenant_site_unit_log_data_fields_path(@tenant, @site, @unit), flash: { :notice => "Import Failure : PLease check CSV"}
    end

    redirect_to import_admin_tenant_site_unit_log_data_fields_url(@tenant, @site, @unit), notice:"Imported tags !"
  end
q3qa4bjr

q3qa4bjr1#

如果您在控制器的中间(不是最后一行)调用renderredirect_to,您也应该使用return来停止当前的执行路径:

return redirect_to(...)

redirect_to(...) and return

更多信息:https://api.rubyonrails.org/v7.0.4/classes/ActionController/Redirecting.html

相关问题