【问题标题】:Circular dependency detected while autoloading constant Product自动加载常量产品时检测到循环依赖
【发布时间】:2014-02-10 18:52:07
【问题描述】:

我正在关注 railscasts 教程。我试图复制他们的教程之一,该教程是关于将 CSV 和 Excel 文件导入到 rails 页面,但我收到循环依赖错误。

尝试了以下解决方案,但没有解决问题:

  1. 重新订购 gems 和包更新/安装它
  2. 将我的 rails 从 4.0.2 降级到 4.0.0

请提供更多解决方案。提前致谢。

查看:test.html.erb

<% provide(:title, 'CSV Import Test')%>

<div class="center hero-unit">
<h3> Test - CSV file import </h3>
</div>

<h4> Import .csv file </h4>

<%= form_tag import_products_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

<h4> Products </h4>
<table id="products">
  <tr>
    <th> Id </th>
    <th> Tagnumber </th>
    <th> IsEnabled </th>
  </tr>

<% @products.each do |product| %>
 <tr>
   <td><%= product.id_pass %></td>
   <td><%= product.tagnumber %></td>
   <td><%= product.isenabled %></td>  
 </tr>
<% end %>

</table>

型号:product.rb

Class Product < ActiveRecord::Base
    attr_accessible :id_pass, :tagnumber, :isenabled

    def self.import(file)
      CSV.foreach(file.path, headers: true) do |row|
      Product.create! row.to_hash
    end
  end

控制器:products_controller.rb

class ProductsController < ApplicationController
  def test
    @products = Product.order(:id_pass)
  end

  def import
    Product.import(params[:file])
    redirect_to root_url, notice: "Data imported."
  end
end

配置:routes.rb

resources :products do
  collection { post :import}
end

..
..
match '/test', to: 'products#test', via: 'get'

【问题讨论】:

    标签: ruby-on-rails-4


    【解决方案1】:

    好的,这些宝石真的很好用:

    https://github.com/liangwenke/to_xls-rails

    它们是非常简单的宝石,但它们使这项任务变得非常快。我在这里为rails 4写了一个清晰的教程:

    https://github.com/liangwenke/to_xls-rails/wiki/Install%20Guide

    您也可以按照作者的说明进行操作,但我发现它们很难。

    在您的控制器中:

    class ProductsController < ApplicationController
        def test
          @products = Product.order(:id_pass)
    
          respond_to do |format|
            format.xls { send_data(@posts.to_xls) }
            # format.xls {
            #   filename = "products-#{Time.now.strftime("%Y%m%d%H%M%S")}.xls"
            #   send_data(@products.to_xls, :type => "application/excel; charset=utf-8; header=present", :filename => filename)
            # }
          end
        end
      end
    

    在你看来:

     <%= link_to "Excel", product_path(:format => :xls) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多