在rails 3路由中使用除以下内容之外的变量:id

时间:2012-05-16 18:55:18

标签: ruby-on-rails routes

我正在尝试让我的rails 3应用程序使用类似于以下的路线:

exampleapp.com/patients/123456

而不是

exampleapp.com/patients/1

其中“123456”将与患者的医疗记录编号(:mrn)相关联,该编号已在:patients表中,并且是唯一的整数。我想使用:mrn代替通常的:id。我该怎么做呢?

对不起,如果已经被问到这个问题 - 我找不到关于我正在尝试做什么的术语。谢谢!

3 个答案:

答案 0 :(得分:6)

你可以这样做,

class Patient < ActiveRecord::Base
  self.primary_key = "mrn"
end

然而,这将改变一堆其他的东西。 to_params将使用mrn。控制器仍将使用params [“id”],但该值将是mrn字段。 Patient.find方法适用于mrn字段,但不适用于id字段。 (您可以使用Patient.find_by_mrn和Patient.find_by_id来处理它们指定的字段。)此外,所有外键都将是mrn值。

您可以编辑mrn字段,但仍然会有一个id字段(除非您将其关闭),但编辑可能会很麻烦,因为所有外键都必须更正。

或者,如果您只想更改URL,则在config / routes.rb文件中而不是

resources :patient

使用

match "/patients/:mrn" => "patients#show"
match "/patients/:mrn" => "patients#update", :via => :put

答案 1 :(得分:5)

您可以将其添加到您的患者模型中

def class Patient < ActiveRecord::Base
  self.primary_key = "mrn"  
end

答案 2 :(得分:1)

您可以通过在Resource实例上重新定义member_scope和nested_scope方法来获得每资源标识符自定义。

resources :patients do
  @scope[:scope_level_resource].tap do |u|
    def u.member_scope
      "#{path}/:mrn"
    end

    def u.nested_scope
      "#{path}/:#{singular}_mrn"
    end
  end
end
相关问题