Rails redirect_to将转向索引页面而不是show

时间:2014-09-12 15:19:03

标签: ruby-on-rails redirect

我正在建造一个没有桌子的模型。意图是我希望它表现得像一个模型,但我只需要一个对象的实例。我的模型类的核心看起来像

class JobScheduler
  include ActiveModel::Model

  @@job_scheduler_instance = nil

  attr_accessor :timeout

  # Public: Override the ActiveModel initialize method to set the
  # job_scheduler_instance.  This is used by the JobScheduler::new
  # method to determine whether to create a new job_scheduler instance
  # or return the existing one.
  def initialize(*args)
    super

    Rails.logger.warn "JobScheduler instance already exists!" if @@job_scheduler_instance
    @@job_scheduler_instance ||= self
  end

  def id
    '1'
  end

  def to_param
    '1'
  end

  class << self
    # Public: Modify the ::new method to return the job_scheduler_instance
    # determined during #initialize.  This is designed to ensure that
    # only one scheduler instance is created at a time.
    #
    # Returns a JobScheduler instance.
    def new(*args)
      super
      @@job_scheduler_instance
    end

    # Public: Returns the job scheduler instance (if defined).
    #
    # Returns a JobScheduler instance.
    def all
      Array(@@job_scheduler_instance)
    end

    def find(*args)
      @@job_scheduler_instance
    end

  end
end

我遇到的问题是,对redirect_to @job_scheduler的任何引用似乎都会转到'/ job_schedulers'路由,即index行为。我不清楚为什么会发生这种情况或我能做些什么来解决它。

控制器:

# GET /job_schedulers/new
def new
  @job_scheduler = JobScheduler.new
  redirect_to @job_scheduler
end

但是当我访问/job_schedulers/new时,我收到错误:No route matches [GET] "/job_schedulers"但我希望它会尝试指向路线/job_schedulers/1

现在,当我将控制器更改为

# GET /job_schedulers/new
def new
  @job_scheduler = JobScheduler.new
  redirect_to job_schduler_url(@job_scheduler)
end

我确实得到了重定向到/job_schedulers/1的预期结果,但我不明白为什么会这样,但上面没有。

路线:

  resources :job_schedulers, only: [:show, :new, :create, :destroy]

有什么想法吗?

...谢谢

1 个答案:

答案 0 :(得分:0)

我认为redirect_to在使用语法时会使用对象的id

redirect_to @instance_variable

有关详细信息,请参阅here

因为您只实例化了对象,所以它没有id。在调用redirect_to之前保存对象将使用id创建对象的记录,并且应该可以解决您的问题。