首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >link_to:action =>'create'去索引而不是'create'

link_to:action =>'create'去索引而不是'create'
EN

Stack Overflow用户
提问于 2018-05-08 05:18:22
回答 2查看 0关注 0票数 0

我正在构建一个相当简单的配方程序来学习RoR,并且我试图让用户通过单击链接而不是通过表单来保存配方,因此我通过link_to连接了user_recipe控制器的“创建”功能。

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

我写了link_to as

代码语言:javascript
复制
<%= "save this recipe", :action => 'create', :recipe_id => @recipe %>

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

控制器看起来像这样

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-05-08 13:59:42

在标准REST方案中,索引操作和创建操作都具有相同的url(/recipes),并且仅在使用GET访问索引和使用POST访问create时不同。因此,link_to :action => :create只需简单地生成一个链接,/recipes浏览器就会/recipes在单击时执行GET请求,从而调用索引操作。

要调用create action use link_to {:action => :create}, :method => :postlink_to明确地告诉你需要一个post请求,或者使用一个带有submit按钮而不是链接的表单。

票数 0
EN

Stack Overflow用户

发布于 2018-05-08 14:48:36

假设你有你的路由文件中设置的默认资源,即类似的东西

代码语言:javascript
复制
resources :recipes

以下内容将生成一个链接来创建一个配方; 即将被路由到创建操作。

代码语言:javascript
复制
<%= link_to "Create Recipe", recipes_path, :method => :post %>

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

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

代码语言:javascript
复制
<%= link_to "All Recipes", recipes_path %>

这假定默认是一个Get HTTP请求。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档