我正在構建一個相當簡單的食譜應用程序來學習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
非常感謝Sepp2k,它不僅提供了答案,還解釋了爲什麼這麼清楚。我真的很難理解爲什麼Rails會做或者期待某些特定的位,而且在線答案通常只會給出'這是如何做'的,沒有原因。你的回答很完美! – pedalpete 2010-09-17 21:12:38
'link_to {:action =>:create},:method =>:post'用data-method =「POST」屬性創建一個鏈接。這是由JavaScript使用的創建一個離散的形式和張貼它。鏈接本身不能用於發送GET請求以外的任何內容,這是JS失敗時會發生的情況。 – max 2017-04-16 07:50:25