4

我有一个名为 的模型Student,其中有一个名为的属性University_ID

我创建了一个自定义操作和路由,通过以下链接显示特定学生的详细信息:students/2/detailsstudents/: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。

我的控制器看起来像这样,如果这有任何帮助:

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

我也尝试过,@student = Student.find(params[:university_id])但没有,没有任何效果。

4

1 回答 1

1

在与@teenOmar 交谈以澄清要求后,这是我们提出的解决方案,它允许现有students/:id/details路由接受 anid或 a university_id(以 a 开头w),并使用 abefore_filter填充@student以用于各种控制器操作:

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
于 2013-04-03T23:51:05.043 回答