2010-09-02 59 views
0

我有一個窗體,我正試圖做一個非常簡單的CRUD操作與MongoDB軌道。param通過爲無軌道形式

我有我的控制器

class RecipesController < ApplicationController 
    def new 
    @recipe = Recipe.new 
    end 

    def update 
    end 

    def create 
    recipe = Recipe.create(params[:title]) 
    redirect_to params[:title] 
    @recipes = Recipe.all 
    end 

    def index 
    @recipes = Recipe.all 
    end 
end 

我的形式

<%= form_for Recipe.new do |f| -%> 

<%= f.text_field :title %> 

<%= f.submit "Create Recipe" %> 

<% end %> 

似乎很基本的給我。 但是,params沒有看到控制器。

我可以看到通過使用WEBrick

Started POST "/recipes" for 127.0.0.1 at 2010-09-02 14:15:56 -0800 
    Processing by RecipesController#create as HTML 
    Parameters: {"authenticity_token"=>"8oyq+sQCAEp9Pv864UHDoL3TTU5SdOXQ6hDHU3cIlM 
Y=", "recipe"=>{"title"=>"test"}, "commit"=>"Create Recipe"} 
Rendered recipes/create.html.erb within layouts/application (4.0ms) 
Completed 200 OK in 51ms (Views: 16.0ms) 

通過PARAMS但redirect_to的PARAMS [:標題]返回零值誤差。

我注意到'title'在'recipe'參數內,並不確定這是否可能是問題的一部分。

讓我感到困惑的很多事情之一是我從來沒有真正需要調用create?是對的嗎?我在窗體上調用'new',由於某些原因,rails自動調用'create'?

回答

1

嘗試把重定向在控制器後@recipes = Recipe.all像這樣,並使你的變量,實例變量:

def create 
    @recipe = Recipe.new(params[:title]) 
    @recipes = Recipe.all 
    respond_to do |format| 
    if @recipe.save 
     format.html redirect_to params[:title] 
    end 
    end 
end 

你的語法相當難看。我建議使用開箱即用的Rails生成器來支撐您的工作,並將您的項目建立在此基礎之上,直到您熟練掌握您的工作。

梁2:

script/generate scaffold Recipe name:string ingredients:text 

的Rails 3:

rails g scaffold Recipe name:string ingredients:text 

然後確保你rake db:migrate

+0

感謝旅行,儘管在寫好ruby之前,你對使用生成器的評論有點像我想學的東西,而且我也沒有發現生成器是很好的學習工具。我一直在努力弄清楚語法,但還沒有找到一個很好的指導。有什麼建議麼? – pedalpete 2010-09-02 22:42:54

+0

開始的第一個好地方是www.tryruby.org。在那之後,我肯定至少會記住自動生成的控制器是如何工作的,並以此爲基礎開展工作。從你的帖子看起來,在你獨自闖入荒野之前,仍然可以從中獲得一些好的東西。此外,Lynda.com,railscasts.com,peepcode.com和官方的Rails API網站也是不錯的選擇。更不用提stackoverflow了。 :d – Trip 2010-09-03 04:21:27

0

正如你建議title參數是你recipe組參數內。因此,要創建您的配方,您需要:

Recipe.create(params[:recipe]) 

注意:如果配方上的驗證失敗,這將返回false並且不創建配方 - 例如,如果你需要一個標題。你不檢查這個,你可能會想。所以,同樣,如果你想重新定向新配方的標題(我不知道爲什麼你想這樣做可能不是一個有效的位置,但我會繼續你的例子),但是,你需要做的:

redirect_to params[:recipe][:title] 

,或者您可以在新創建的配方r.title訪問稱號。

另外,如果您重定向到另一個操作,則設置實例變量(@recipes)沒有好處,因爲它們在重定向期間會丟失。