Monday, May 16, 2011

Use helpers in controller

Rails applied Restful as part of its design.

To follow Restful, you should:

1. Model your web app as resources
2. Manipulate your app's resources through a conventional interface

Ex:
- if you have Product resource then urls to CRUD (Create, Edit, Update, Delete) this resource would be:

Action Urls Web MethodRestful Interface
Create /products POST products_url
Edit /products/1/edit POST edit_product_url
Update /products PUT product_url
Delete /products DELETE product_url

Then to get links to delete/edit a product through Restful interface, we can use link_to method as below:

link_to 'Edit', edit_product_path(product)

link_to 'Remove', product_path(product), :confirm => 'Are you sure?', 
        :method => :delete

By default, you can only use above interfaces in View layer. How can we use those in Controller layer?
  • In Rails 2, call through @template variable
    @template.link_to('Edit', edit_product_path(product))
  • In Rails 3, call through view_context method
    view_context.link_to('Delete', product_path(product), :confirm => 'Are you sure?', :method => :delete)
References

1 comment: