2014-09-12 46 views
1

我正在構建一個沒有表格的模型。意圖是我希望它像一個模型一樣行事,但我只需要一個對象實例。我的模型類的核心看起來像Rails redirect_to將要索引頁面而不是顯示

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] 

任何想法?

謝謝...

+0

你能顯示你的路線嗎? – Mandeep 2014-09-12 15:25:46

+0

更新了路線。謝謝。 – 2014-09-12 15:41:50

回答

0

我相信redirect_to使用對象的id,使用語法時:

redirect_to @instance_variable 

更多信息,請參見here

因爲您只實例化了該對象,所以它沒有id。在調用redirect_to之前保存對象將創建一個id對象的記錄,並應解決您的問題。

+0

謝謝,我修改了模型以包含def id; '1';結束,所以它會有一個ID,但我仍然有同樣的問題。 – 2014-09-12 16:16:39

+0

@SterlingParamore啊。我自己測試了它並設法重現了這個問題。我使用'@ model.create'來代替'@ model.new'來修復它。也許除了'id'之外,還有其他一些東西不存在,而不是持久化對象。 – 2014-09-12 16:21:14

+0

我確定我只是想念別的東西,我只是不知道那是什麼。 – 2014-09-16 00:01:49

相關問題