How to route the same url to different actions?
我有一个要通过控制器的index动作呈现的页面。我想添加到此页面的链接,该链接将重新加载当前页面,但我希望它首先路由到其他操作。
这是我的routes.rb文件的样子:
1 2 | match 'users/:id/food' => 'foods#index', :as => :foods_show match 'users/:id/food' => 'foods#sell', :as => :food_sell |
我的link_to:
1 | <%= link_to"Sell this Food", food_sell_path(current_user.id) %> |
因此该页面通常是通过foods#index呈现的,但是当用户单击此链接时,我想重新加载当前页面,但要通过与index不同的操作。
控制器代码:
1 2 3 4 5 6 7 8 9 10 | def index @user = User.find(params[:id]) @food = @user.foods end def sell @user = User.find(params[:id]) @food = @user.foods redirect_to foods_show_path(@user.id), :notice =>"You have sold one item!" end |
谢谢!
您不能将相同的url匹配到不同的操作,因为基本上它们是相同的。您需要更改url中的某些内容,或更改动词(get,post,put,delete)或添加一些参数来区分它们。
例如,将
1 2 | get 'users/:id/food' => 'foods#index', :as => :foods_show post 'users/:id/food' => 'foods#sell', :as => :food_sell |
然后在链接中将方法设置为
1 | <%= link_to"Sell this Food", food_sell_path(current_user.id, :_method => 'post') %> |