简体   繁体   中英

Rails find by something other than id for show page

I'm new to rails and I'm working on a site where you can enter yhour judo club and I'm trying to make it so the address is /club/denjudo for example rather than /clubs/2. On the index page I am able to set it up so you can click on the club and it will take you do clubs/denjudo but I cannot get it go access the recofd for the correct club, it seems to select a rendom club and show that info. For the controller I have:

def show 
  @club = Club.find_by(params[:club_username])
end

Any help would be greatly appreciated.

Scott

You want to just specify the attribute you are looking up by. Based on your example.

Club.find_by(username: params[:club_username])

You need to set at routes.rb

 get '/clubs/:club_username', to: 'clubs#show', as: 'club'

Then, make sure that club_username param is unique at your schema.

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