【问题标题】:I can`t access the array that I create with scheduler我无法访问使用调度程序创建的数组
【发布时间】:2018-01-06 03:35:32
【问题描述】:

我每天使用调度程序创建数组。

我想从该数组中获取日期。 但是当我访问索引页时,数组返回 nil。 你知道为什么吗?

例如这样。

schedule.rb

every 1.day, at: '4:30 am' do
  runner 'User.create_user_group'
end

模型/用户.rb

class User < ActiveRecord::Base
    def self.create_user_group
        @user_array = self.all.shuffle
    end
end

控制器/users_controller.rb

class UsersController < ApplicationController
  def index
    @user_array #=> nil
  end
end

【问题讨论】:

    标签: ruby-on-rails arrays ruby ruby-on-rails-4


    【解决方案1】:

    您为什么希望模型类User 的实例变量在控制器类UsersController 中可见?!

    如果您需要控制器中的@users,您需要显式检索它们:

    class UsersController < ApplicationController
      def index
        user_array
      end
    
      def user_array
        @user_array ||= User.all.shuffle
      end
    end
    

    请不要按原样使用上面的代码,因为它有太多其他故障。答案只是解释了你的代码出了什么问题。

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 1970-01-01
      • 2014-12-31
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多