【问题标题】:Empty Array in Controller ...but works in Rails Console控制器中的空数组......但在 Rails 控制台中有效
【发布时间】:2023-03-19 08:25:01
【问题描述】:

我很困惑……

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

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

  • 我已经重启了服务器
  • 我检查了拼写错误(字面意思是将 Distributor.all 从控制器复制并粘贴到 控制台以确保它在控制台中工作)
  • 我已使用 binding.pry 进行调试,没有显示任何问题
  • 我检查了日志,没有出现任何错误
  • 我检查了日志和控制台,并且正在运行相同的 SQL 查询 Distributor Load (10.9ms) SELECT "distributors".* FROM "distributors" 两者,但返回不同的结果
  • 生成 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

分销商 index.html.erb

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


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

【问题讨论】:

  • RheemruudDistributor 是什么?
  • 对不起,不应该在那里。是Distributor.all(代码里写的是Distributor.all,我只是打错了)

标签: ruby-on-rails ruby-on-rails-4 model console


【解决方案1】:

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

【讨论】:

  • 对不起,不应该在那里。是Distributor.all(代码里写的是Distributor.all,我只是打错了)
【解决方案2】:

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

这是一个使用公寓 gem 的多租户应用程序,我必须将这个新创建的模型放入 apartment.rb 初始化程序的排除模型部分。

我想如果其他人处于这种情况,我会留下这个消息。

【讨论】:

    【解决方案3】:

    使用

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

    而不是

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

    在你看来

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多