views:

30

answers:

3

When I visit http://my-application.com/posts/1 in my browser, Rails knows I'm looking for the Post with id = 1. How can I get my application to do this internally? I.e., I'd like a function (call it associate_with_resource) that takes a string containing a URL as its input and outputs the associated resource. For example:

>> associate_with_resource('http://my-application.com/posts/1')
=> #<Post id: 1, ... >

(I'd like to be able to use associate_with_resource throughout my application though -- not only in the console)

A: 

When I visit http://my-application.com/posts/1 in my browser, Rails knows I'm looking for the Post with id = 1.

This is not correct.

In Rails 3, when you put this into routes.rb:

resources :posts

Then Rails will know that you have a controller named PostsController in the file app/controllers/posts_controller.rb. Rails will also know that in your PostsController class, you have seven methods that are intended to be action methods: index, new, create, show, edit, update, delete.

What you do in these action methods is entirely up to you. You may wish to retrieve and display a Post object, or not.

Justice
My mistake. I guess what I'm looking for is a method that will return the `:controller` and `:id` associated with a given route. From there I can do something like `:controller.classify.constantize.find(:id)`
Horace Loeb
+1  A: 

I think I'm looking for the ActionController::Routing::Routes.recognize_path method

Horace Loeb
+1  A: 

You are right about ActionController::Routing::Routes.recognize_path and I would do it like this:

create a file lib/associate_with_resource.rb

module AssociateWithResource
  def associate_with_resource(path)
    url_hash = ActionController::Routing::Routes.recognize_path path
    url_hash[:controller].classify.constantize.find(url_hash[:id])
  end
end

class ActionController::Base
  include AssociateWithResource
  helper_method :associate_with_resource
end

class ActiveRecord::Base
  include AssociateWithResource
end

Now you can call the associate_with_resource(path) from almost everywhere to get the resource belonging to a given path

jigfox