2010-09-17 55 views
18

我正在構建一個相當簡單的食譜應用程序來學習RoR,並且我試圖讓用戶通過單擊鏈接而不是通過鏈接來保存食譜一個表單,所以我通過link_to連接了user_recipe控制器的'create'功能。link_to:action =>'創建'去索引而不是'創建'

不幸的是,由於某些原因,link_to正在調用索引函數而不是create。

我已經寫了的link_to作爲

 
<%= "save this recipe", :action => 'create', :recipe_id => @recipe %> 

這個環節上user_recipes/index.html.erb並調用同一控制器的「創建」功能。如果我包含:控制器,它似乎沒有什麼區別。

的控制器看起來像這樣

 
def index 
    @recipe = params[:recipe_id] 
    @user_recipes = UserRecipes.all # change to find when more than one user in db 
    respond_to do |format| 
     format.html #index.html.erb 
     format.xml { render :xml => @recipes } 
    end 
end 

def create 
    @user_recipe = UserRecipe.new 
    @user_recipe.recipe_id = params[:recipe_id] 
    @user_recipe.user_id = current_user 
    respond_to do |format| 
     if @menu_recipe.save 
     format.html { redirect_to(r, :notice => 'Menu was successfully created.') } 
     format.xml { render :xml => @menu, :status => :created, :location => @menu } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @menu.errors, :status => :unprocessable_entity } 
     end 
    end 

回答

37

在標準的REST方案索引操作和創造行動都具有相同的URL(/recipes),只有在指數不同的是使用GET和創建訪問訪問使用POST。因此,link_to :action => :create將簡單地生成到/recipes的鏈接,這將導致瀏覽器在單擊時執行對/recipes的GET請求,從而調用索引操作。

要調用創建操作,請使用link_to {:action => :create}, :method => :post,明確告訴link_to您需要發佈請求,或者使用帶有提交按鈕而不是鏈接的表單。

+1

非常感謝Sepp2k,它不僅提供了答案,還解釋了爲什麼這麼清楚。我真的很難理解爲什麼Rails會做或者期待某些特定的位,而且在線答案通常只會給出'這是如何做'的,沒有原因。你的回答很完美! – pedalpete 2010-09-17 21:12:38

+0

'link_to {:action =>:create},:method =>:post'用data-method =「POST」屬性創建一個鏈接。這是由JavaScript使用的創建一個離散的形式和張貼它。鏈接本身不能用於發送GET請求以外的任何內容,這是JS失敗時會發生的情況。 – max 2017-04-16 07:50:25

9

假設你已經在你的路由文件中設置了缺省資源,即像這樣

resources :recipes 

下將生成將創建配方的鏈接;即將被路由到創建動作。

<%= link_to "Create Recipe", recipes_path, :method => :post %> 

爲了達到這個目的,JS需要在瀏覽器中啓用。

以下將生成一個鏈接,顯示所有食譜;即將被路由到索引操作。

<%= link_to "All Recipes", recipes_path %> 

這裏假設默認值是Get HTTP請求。