简体   繁体   中英

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. 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. It should have access to user #2's info.

I did some research on stack overflow, and added the following to 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 . 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.

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 :

  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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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