我有一个模型叫 Student
,它有一个名为 University_ID
的属性在里面。
我创建了一个自定义操作和路线,通过以下链接显示特定学生的详细信息:students/2/details
即 students/:id/details
但是,我希望能够允许用户使用他们的大学 ID 而不是数据库 ID,以便以下内容可以工作,例如 students/X1234521/details
即 students/:university_id/details
我的路由文件现在看起来像这样:
resources :students
match 'students/:id/details' => 'students#details', :as => 'details'
但是,这使用 Student_ID 而不是 University_ID,我试过这样做
match 'students/:university_id/details' => 'students#details', :as => 'details'
,但这仅对应于 Student_ID,而不对应于 University_ID。我的 Controller 看起来像这样,如果这有任何帮助:
def details
@student = Student.find(params[:id])
end
我也试过做
@student = Student.find(params[:university_id])
但不,没有任何效果。
最佳答案
在与@teenOmar 交谈以澄清要求后,这是我们提出的解决方案,它允许现有的 students/:id/details
接受 id
的路由或 university_id
(以 w
开头),并使用 before_filter
填充 @student
用于各种 Controller 操作:
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
关于ruby-on-rails - 创建使用模型属性而不是 Rails 中的 ID 的自定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15800114/