2014-02-07 21 views
0

我還是新的軌道和運行成(從我的角度至少)一個相當奇怪的問題: 有一個形式和途徑,並在控制器的方法的視圖。不知何故,該方法被直接調用而不是渲染視圖,等待輸入並將其傳遞給方法。路線跳過視圖,並調用方法馬上

這就是它有點樣子:

控制器

class Some::ThisController < ApplicationController 

    def method_a 
    variable_a = params[:variable_a].to_time 
    variable_b = #other stuff 
    @variable_c = # do stuff with the variable_a & variable_b 

    end 

視圖(method_a.rb)

= form_tag this_method_a_path do 
    = text_field_tag :variable_a 
    = text_field_tag :variable_a 
    = submit_tag 'Apply' 

路線(some.rb)

The::Application.routes.draw do 

    namespace :some do 

    # leave all the unimportant stuff 

    match this/method_a => this#method_a, :as => :method_a 

那麼我的問題是什麼? 的觀點並沒有被渲染 - 我只得到:對於無 未定義的方法`TO_TIME」:NilClass 當我重新命名視圖渲染精細的方法。

我想要什麼? 要渲染的視圖,所以我可以填寫表單並提交它,然後讓方法返回@variable_c中的任何內容。

我無法弄清楚什麼不順心。也許是太晚了今天......

回答

1

您需要兩個單獨的控制器方法,一個渲染視圖和一個接受提交表單。當您在method_a中時,params[:variable_a]將不可用,因爲表單尚未提交,只是呈現!當用戶點擊提交按鈕

= form_tag method_b_path do 
    = text_field_tag :variable_a 
    = text_field_tag :variable_b 
    = submit_tag 'Apply' 

試試這個:

class Some::ThisController < ApplicationController 

    def method_a 
    # nothing, just let Rails render the method_a view 
    end 

    # this will accept the submission of the form 
    def method_b 
    variable_a = params[:variable_a].to_time # this will now be available because the user has submitted the form 
    variable_b = #other stuff 
    @variable_c = # do stuff with the variable_a & variable_b 

添加新的方法到路線:

The::Application.routes.draw do 

    namespace :some do 

    # leave all the unimportant stuff 

    get 'some/method_a' => 'some#method_a', :as => :method_a 
    post 'some/method_b' => '[email protected]_b'. :as => :method_b 

現在你的觀點會參數:variable_a:variable_b將被髮送到您的c中的method_b動作您可以撥打params[:variable_a]或b。

如果你不明白這是如何工作,也許這將有助於:

  • 用戶訪問路徑GET /some/method_a和您的應用程序接收在你的控制器中的method_a行動的請求,並通過渲染method_a.html.erb視圖響應。
  • 的形式呈現,並且用戶填寫表格,然後點擊提交發送請求在您的控制器的method_b行動。除了這個請求之外,還包含text_fields的參數,然後您可以將其用於計算。

Hope that's clear enough.

+0

我知道它就是這樣的!謝謝。 只是出於好奇,因爲它似乎是爲其他人工作。在方法本身中有沒有辦法做到這一點? – tomr

+0

這不是一個好的做法,但是,你必須首先檢查是否存在params。你的路線只需要「匹配」,儘管它可以接受任何HTTP動詞。 – DiegoSalazar

-1

嗯,這完全取決於你怎麼稱呼你的路線。

這是一個獲取請求嗎?一個由url定義的「variable_a」?在這種情況下,你沒有在你的路線中定義它,所以它變爲空...

或者它是一個post/patch請求?在這種情況下,您最有可能將表單張貼到路由中,並因此發佈到控制器方法中......但您首先需要呈現表單。

所以,你應該是:

在你的控制器的方法來調用表單視圖「得到」

在你的情況下,就這麼簡單在你的路由添加:

match "this/method_a", to: "controller#draw_form", via: 'get' 

在你的控制器

def draw_form 
    render "method_a" 
end 

,然後,當你的表單提交到相同url(你的路由中的「this/method_a」),你的控制器中將會有你的method_a動作處理的參數。

+0

仍然試圖找出那個投票...不惱火,只是困惑... –