2

コントローラーの index アクションを介してレンダリングしているページがあります。現在のページをリロードするリンクをこのページに追加したいのですが、最初に別のアクションにルーティングしたいと考えています。

これが私の routes.rb ファイルの外観です。

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

そして私のlink_to:

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

したがって、ページは通常、foods#index を介してレンダリングされますが、ユーザーがこのリンクをクリックすると、現在のページを再読み込みしたいのですが、index とは異なるアクションを介します。

コントローラーコード:

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

ありがとう!

4

1 に答える 1

6

基本的に同じ URL を異なるアクションに一致させることはできません。URL の何かを変更するか、動詞 (get、post、put、delete) を変更するか、パラメータを追加してそれらを区別する必要があります。

たとえば、getインデックスとpost販売に次のように使用します。

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 に答える