tkymtk
tkymtk

Reputation: 2705

How do rails extract an id from an instance variable?

I'm reading "Rails Routing from the Outside In" on RailsGuides.

In Section 1.2, it says

<%= link_to 'Patient Record', patient_path(@patient) %>

will generate the path /patients/17.

What I'd like to know is how rails extract the id from the instance variable. I've been trying to find the corresponding line of the code on GitHub but can't find.

Upvotes: 0

Views: 149

Answers (3)

Adeptus
Adeptus

Reputation: 683

method responsible is to_param. link to line on github

Upvotes: 0

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

The ID comes from calling #to_param on the object. Here is a little documentation about it, http://guides.rubyonrails.org/active_support_core_extensions.html#to-param

Upvotes: 1

synapse
synapse

Reputation: 5728

It calls a to_param method which by default will produce the ID. You can override it to produce nice URLs like this

class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{title}"
  end
end

Upvotes: 1

Related Questions