控制器中的空数组..但在 Rails 控制台中工作



我很困惑...

我有一个名为 Distributor 的模型,当我在控制台中执行 Distributor.all 时,我会得到所有记录的数组(根据此查询,目前有 657 条记录)。

但是,我创建了一个控制器操作以在索引视图中显示此分发服务器。并且从同一查询 Distributor.all 返回一个空数组

  • 我已重新启动服务器
  • 我已经检查了拼写错误(从控制器到控制台以确保它在控制台中工作)
  • 我已经使用 binding.pry 进行调试,那里没有显示任何问题
  • 我已经检查了日志,没有显示任何错误
  • 我已经检查了日志与控制台,并且正在运行相同的SQL查询 分发服务器负载(10.9ms) 选择"分销商"。 从两者的"分销商",但返回不同的结果
  • 生成CSV或HTML不是问题,因为两者都加载没有错误

有什么建议吗?

分销商型号:

class Distributor < ActiveRecord::Base
belongs_to :brand
def self.to_csv
    attributes = %w{distributor_id mfg_brand_id company_name address_one address_two city state postcode country address_type primary_address users_count created_at}
    CSV.generate(headers: true) do |csv|
        csv << attributes
        all.each do |d|
            csv << d.attributes.values_at(*attributes)
        end
    end
  end   
end 

分配器控制器

class DistributorsController < ApplicationController
before_action :authenticate_user!
def index
    @user = current_user
    if @user.admin?
      @distributors = Distributor.all
      respond_to do |format|
        format.html
        format.csv { send_data @distributors.to_csv }
      end
    else
     flash["danger"] = "You must be a logged in Admin to  access this route"
     redirect_to root_path
    end
  end   
end

分销商指数.html.erb

<h1>Distributors#index</h1>
<p>Find me in app/views/distributors/index.html.erb</p>

<%= @distributors.each do |d| %>
    <%= d %>
<% end %>

在你的控制器中,如果你用@distributors = Distributor.all替换@distributors = RheemruudDistributor.all,它应该可以工作,对吧?还是我错过了什么?

终于想通了...我认为这很简单。

这是一个使用公寓宝石的多租户应用程序,我不得不将这个新创建的模型放在 apartment.rb 初始值设定项的排除模型部分。

我想我会离开这个听证会,以防其他人在这种情况下。

使用

<% @distributors.each do |d| %>
    <%= d %>
<% end %>

而不是

<%= @distributors.each do |d| %>
    <%= d %>
<% end %>

在您的视野中

最新更新