简体   繁体   English

Rails路由错误:NoMethodError

[英]Rails route error: NoMethodError

I'm new to Rails, and am trying to create a page that is largely a copy of my users#show page, with slightly different content and formatting. 我是Rails的新手,正在尝试创建一个页面,该页面基本上是我的users#show页面的副本,内容和格式略有不同。 Ideally, this would work something like this: 理想情况下,这会像下面这样工作:

Normal route: http://myUrl.com/users/2 New route: http://myUrl.com/users/2/lightbox <-this is the new route with the formatting. 普通路由: http : //myUrl.com/users/2新路由: http : //myUrl.com/users/2/lightbox <-这是具有格式的新路由。 It should have access to user #2's info. 它应该有权访问用户#2的信息。

I did some research on stack overflow, and added the following to routes.rb 我对堆栈溢出进行了一些研究,并将以下内容添加到routes.rb

    resources :users do
      member do
       get 'lightbox'
      end
    end

and then raked the routes. 然后倾斜路线。 This allows me to type in the url http://myUrl.com/users/2/lightbox . 这使我可以输入url http://myUrl.com/users/2/lightbox However, it doesn't seem to have access to any of the user class's resources, and seems to have no idea who User #2 is. 但是,它似乎无权访问任何用户类的资源,并且似乎不知道用户#2是谁。

I may completely have gone about this the wrong way - all I really want to do is create a custom page to display an individual user's information that's different from the show page. 我可能完全采用了错误的方式-我真正想做的就是创建一个自定义页面,以显示与显示页面不同的单个用户的信息。 I'd really appreciate any help! 我真的很感谢您的帮助!

You need to add an action to your app/controllers/users_controller.rb : 您需要向您的app/controllers/users_controller.rb添加一个操作:

  def lightbox
    @user = User.find(params[:id]
    # any other logic, look at your show method
  end

Routing only maps a url to a controller action. 仅路由将URL映射到控制器动作。 It is up to the controller action, each individually, to set variables and render the view. 设置变量和渲染视图完全取决于控制器的动作。

Before filters and helper methods are used make sure you don't have to write code a bunch of times. 在使用过滤器和辅助方法之前,请确保您不必多次编写代码。 For example: 例如:

before_filter :find_user, only: [ :show, :lightbox ]

def show
end

def lightbox
end

protected

def find_user
  @user = User.find(params.fetch :id)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM