【问题标题】:Rails4: Link to A ControllerRails4:链接到控制器
【发布时间】:2013-08-18 19:33:19
【问题描述】:

我有一个用户的显示页面

1.) 路线

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

2.) 用户控制器.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 的新手,如果有人能启发我,那就太好了:)

【问题讨论】:

  • 嗨。您真的要按名称查找用户吗?我认为使用 id 是一种更好的方法。
  • 严格的视觉和功能。但我不认为这是问题:(
  • 我认为我的链接是错误的。但我仍然在黑暗中。
  • 你能把你的 Shop 和 Listing 类放在这里吗?这是一个很小的问题,我正在写答案。
  • 类是什么意思? :/ 我是 Rails 新手,还在学习 :) 抱歉

标签: ruby-on-rails undefined ruby-on-rails-4 rails-routing


【解决方案1】:

首先根据 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'

【讨论】:

  • 仍然收到该错误。我认为这与 rails 如何获取 shop :id 或知道链接到哪里有关。
  • 由于您使用了as: :shop,您应该可以使用&lt;%= link_to 'My Shop', shop_path(@user) %&gt; 创建链接。
猜你喜欢
  • 2014-07-04
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 2012-10-18
  • 2013-08-21
  • 2013-04-18
相关资源
最近更新 更多