ped*_*ete 18 ruby-on-rails link-to
我正在构建一个相当简单的配方应用程序来学习RoR,我试图通过单击链接而不是通过表单来允许用户保存配方,所以我通过link_to连接user_recipe控制器的'create'功能.
不幸的是,由于某种原因,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
sep*_*p2k 39
在标准REST方案中,索引操作和创建操作都具有相同的url(/recipes),并且仅在使用GET访问索引并且使用POST访问create时才有所不同.因此,link_to :action => :create只需生成一个链接,/recipes该链接将导致浏览器/recipes在单击时执行GET请求,从而调用索引操作.
要调用create action link_to {:action => :create}, :method => :post,请link_to明确告知您要发布请求,或使用带有提交按钮而非链接的表单.
Yus*_*ber 11
假设您在路径文件中设置了默认资源,即类似这样的东西
resources :recipes
Run Code Online (Sandbox Code Playgroud)
以下将生成一个将创建配方的链接; 即将被路由到创建操作.
<%= link_to "Create Recipe", recipes_path, :method => :post %>
Run Code Online (Sandbox Code Playgroud)
为此,需要在浏览器中启用JS.
以下将生成一个显示所有食谱的链接; 即将被路由到索引操作.
<%= link_to "All Recipes", recipes_path %>
Run Code Online (Sandbox Code Playgroud)
这假定默认值是Get HTTP请求.
| 归档时间: |
|
| 查看次数: |
29252 次 |
| 最近记录: |