2

I have a page that I'm rendering through the index action of a controller. I want to add a link to this page, which will reload the current page, but I want it to route to a different action first.

Here's what my routes.rb file looks like:

match 'users/:id/food' => 'foods#index', :as => :foods_show
match 'users/:id/food' => 'foods#sell', :as => :food_sell

And my link_to:

<%= link_to "Sell this Food", food_sell_path(current_user.id) %>

So the page is normally rendered via foods#index, but when a User clicks on this link, I want to reload the current page but via a different action than index.

Controller code:

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

Thanks!

4

1 回答 1

6

您不能将相同的 url 匹配到不同的操作,因为它们基本上是相同的。您需要更改 url 中的某些内容,或更改动词(get、post、put、delete)或添加一些参数来区分它们。

例如,使用getfor index 和postfor sell:

get 'users/:id/food' => 'foods#index', :as => :foods_show
post 'users/:id/food' => 'foods#sell', :as => :food_sell

并在您的链接中将方法设置为post

<%= link_to "Sell this Food", food_sell_path(current_user.id, :_method => 'post') %>
于 2013-05-04T02:52:26.877 回答