I have a model called Student
, which has an attribute called University_ID
in it.
I created a custom action and route which displays the details of a specific student via the following link :students/2/details
i.e. students/:id/details
However, I want to be able to allow the user to use their university ID instead of the database ID so that the following would work for instance students/X1234521/details
i.e. students/:university_id/details
My route file looks like this at the moment:
resources :students
match 'students/:id/details' => 'students#details', :as => 'details'
However this uses the Student_ID as opposed to the University_ID, and I've tried doing
match 'students/:university_id/details' => 'students#details', :as => 'details'
, but that only corresponds to the Student_ID, not the University_ID.
My controller looks like this, if this helps in any way:
def details
@student = Student.find(params[:id])
end
I also tried doing @student = Student.find(params[:university_id])
but nope, nothing worked.
After chatting with @teenOmar to clarify the requirements, here's the solution we came up with, which allows for the existing students/:id/details
route to accept either an id
or a university_id
(which starts with a w
), and uses a 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