3

我有一个用户的显示页面,其中

1.) 路线

get 'users/:id' => 'user#show', as: :user

2.) user_controller.rb

class UserController < ApplicationController

before_filter :authenticate_user!, only: :show

def show
    @user = User.find_by_name(params[:id]) # for name instead of id
@listings = @user.listings
end
end

我可以通过“ current_user ”链接到它。

我想创建一个 Shop Controller,所以我遵循了相同的步骤。我生成了一个 Shops Controller 并修改了路由和控制器,如下所示:

1.) 路线

get 'users/:id' => 'user#show', as: :user
get 'shop/:id' => 'shop#show', as: :shop

2.) shop_controller.rb

class ShopController < ApplicationController

before_filter :authenticate_user!, only: :show

def show
    @user = User.find_by_name(params[:id]) # for name instead of id
    @listings = @user.listings
end

end

这仅适用于我在用户页面(localhost:3000/users/test)然后单击控制器的链接。然后切换到 (localhost:3000/shop/test)。

如果我尝试在我得到的其他任何地方单击链接

在此处输入图像描述

链接是->

<li><%= link_to "My Shop", :controller => "shop", :action => "show" %></li>

我对Rails相当陌生,如果有人能启发我,那就太好了:)

4

1 回答 1

2

首先根据 Rails 约定更正控制器的名称。名称应如下所示。

控制器/ users_controller.rb

class UsersController < ApplicationController

before_filter :authenticate_user!, only: :show

    def show
        @user = User.find(params[:id]) # Because Id can't be same for two users but name can be.
        @listings = @user.listings
    end
end

在 shop_controller 的情况下很好,因为 shop 不是模型。

控制器/ shop_controller.rb

class ShopController < ApplicationController

before_filter :authenticate_user!, only: :show

def show
    @user = User.find(params[:id]) # Id can't be same for two users but name can be.
    @listings = @user.listings
end

end

并给出这样的链接。

<%= link_to "My Wonderful Shop", {:controller => "shop", :action => "show", :id => @user.id} %>

在您的路线文件中

get 'shop/:id' => 'shop#show'
于 2013-08-18T19:45:39.957 回答