This project is archived and is in readonly mode.

#1716 ✓stale
Matthew Moore

ActiveResource should use to_param to generate routes

Reported by Matthew Moore | January 9th, 2009 @ 09:06 AM | in 3.x

Let's say you have a resource that uses a permalink to_param, instead of id.

To find this using ActiveResource, you'd usually do something like:


ar = MyActiveResource.new :id => 'my-permalink'  
ar.id                            #=> 'my-permalink'

ar.get(:custom_action)
ar.id                            #=> 5

However, this causes problems for the next call you do to 'ar', because id will be over-written by the ID of the object, not the permalink.

If you did a subsequent call again (or a save), you'd get a 404, because you're actually sending the ID, not the permalink.


ar.get(:custom_action)
ar.save

Instead, the solution should be to let you set a to_param method in your ActiveRecord class that can be overridden in 'permalink'-style cases. E.g.:


MyActiveResource < ActiveResource::Base
  def to_param
    self.permalink
  end
end

So the following would work:


ar = MyActiveResource.new :permalink => 'my-permalink'  
ar.id                                        #=> nil
ar.permalink                            #=> 'my-permalink'
ar.to_param                             #=> 'my-permalink'

ar.get(:custom_action)
ar.id                                        #=> 5
ar.permalink                            #=> 'my-permalink'
ar.to_param                             #=> 'my-permalink'

ar.get(:custom_action)  # now works!
ar.save    # now works!

Any thoughts appreciated before I dive in and take the time to submit the patch!

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Pages