首页 文章

link_to:action => 'create'转到索引而不是'create'

提问于
浏览
18

我 Build 一个非常简单的食谱应用程式学习的回报率,而我试图允许用户通过单击链接而不是通过一种形式来保存配方,所以我连接user_recipe控制器通过的link_to“创造”的功能 .

不幸的是,由于某种原因,link_to正在调用索引函数而不是create .

我把link_to写成了

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

此链接位于user_recipes / index.html.erb上,并且正在调用同一控制器的“create”功能 . 如果我包含:controller,它似乎没有什么区别 .

控制器看起来像这样

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

2 回答

  • 38

    在标准REST方案中,索引操作和创建操作都具有相同的URL( /recipes ),并且仅在使用GET访问索引并且使用POST访问create时不同 . 所以 link_to :action => :create 将只生成一个到 /recipes 的链接,这将导致浏览器在单击时执行 /recipes 的GET请求,从而调用索引操作 .

    要调用create动作,请使用 link_to {:action => :create}, :method => :post ,明确告诉 link_to 您想要发布请求,或使用带有提交按钮而不是链接的表单 .

  • 9

    假设您在路由文件中设置了默认资源,即类似这样的东西

    resources :recipes
    

    以下将生成一个将创建配方的链接;即将被路由到创建操作 .

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

    为此,需要在浏览器中启用JS .

    以下将生成一个显示所有食谱的链接;即将被路由到索引操作 .

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

    这假设默认值是Get HTTP请求 .

相关问题