Create custom routes that use the model attribute instead of an identifier in Rails

I have a model called Student that has the University_ID attribute in it.

I created a custom action and route that displays information about a particular student at the following link: students/2/details ie students/:id/details

However, I want to be able to allow the user to use their university identifier instead of the database identifier, for example, the following: students/X1234521/details i.e. students/:university_id/details

Currently, my route file is as follows:

 resources :students match 'students/:id/details' => 'students#details', :as => 'details' 

However, this uses Student_ID as opposed to University_ID, and I tried doing

match 'students/:university_id/details' => 'students#details', :as => 'details' ,: match 'students/:university_id/details' => 'students#details', :as => 'details' , but this only matches Student_ID, not University_ID.

My controller looks like this if it helps anyway:

 def details @student = Student.find(params[:id]) end 

I also tried doing @student = Student.find(params[:university_id]) , but nothing, nothing worked.

+4
source share
1 answer

After talking with @teenOmar, to clarify the requirements, here is a solution we developed that allows the existing students/:id/details route to accept either id or university_id (which starts with w ) and uses before_filter to populate @student for use in various controller actions:

 class StudentsController < ApplicationController before_filter :find_student, only: [:show, :edit, :update, :details] def show # @student will already be loaded here # do whatever end # same for edit, update, details private def find_student if params[:id] =~ /^w/ @student = Student.find_by_university_id(params[:id]) else @student = Student.find(params[:id]) end end end 
+1
source

All Articles