Pages

Showing posts with label Rails Princlples. Show all posts
Showing posts with label Rails Princlples. Show all posts

Friday, November 21, 2014

Simple, user-friendly cancel links for your Rails forms



The default Rails view generator includes back links on form-related view templates, so if users change their mind they can easily get out of the form and on to something else. However, these links are static. What do you do if you allow users to access the form from multiple views (say, an index and a show).
Here’s a simple but effective solution I came up with: Instead of passing a static URL, I pass the HTTP referrer environment variable as the location. That way users are taken back to the page from which they opened the form to begin with.
Here’s how it works. Most of the code resides in the application_helper.rb file:
  module ApplicationHelper
    include Rails.application.routes.url_helpers

    def cancel_link
      return link_to 'Cancel', request.env["HTTP_REFERER"], 
        :class => 'cancel', 
        :confirm => 'Are you sure? Any changes will be lost.'
    end
  end
You’ll need to include Rails.application.routes.url_helpers in order to access link_to from a helper method. Then you add the helper method itself, which does nothing more than return a cancel link. Mine uses an old-style :confirm message; you can spruce it up with some less obtrusive if you’d like.
If I need a cancel link in a view, I just add
  <%= cancel_link %>
The result: a flexible, reusable cancel option that’s much more user-friendly.

Friday, December 27, 2013

ORM for Rails

ActiveRecord: Object-Relational Mapping(ORM) for Rails


  • Object Relational Mapping (ORM): simplify the use of databases in applications.
    • Use objects to hold database records
      • One class for each table in the database
      • Objects of the class correspond to rows in the table
      • Attributes of an object correspond to columns from the row
    • Manage the movement of information between objects and the back-end database.
    • Manage relationships between tables (joins), turn into linked data structures.

Tuesday, December 24, 2013

Convention over Configuration in Rails

Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your BooksController class:
class BooksController < ApplicationController
end
And the following in your routes file:
resources :books

And you have a view file app/views/books/index.html.erb:
<h1>Books are coming soon!</h1>
Rails will automatically render app/views/books/index.html.erb when you navigate to /booksand you will see "Books are coming soon!" on your screen.