Rails Coach

Rails Coach

By Charles Max WoodTechnology
Download on the App Store

Rails Coach episodes

  • ActiveModel – Making Ruby Classes Behave Like Models
    I’ve been working on an ORM for Cassandra. One of the things I’ve been using to build the ORM is ActiveModel. ActiveModel gives you modules you can add to your class that makes it behave like an ActiveRecord Model.
    Here are some of the features you can add to your classes with ActiveModel.
    Attribute Methods
    Callbacks
    Dirty Attributes (knowing which attributes have changed)
    Naming (allows you to reference the class and model by the object)
    Observers
    Serialization (to JSON or XML)
    State Machine (a really basic one)
    Translation
    Validations
    So, if you’re looking to add your Ruby class to a Rails app, or want this sort of behavior in Sinatra, etc. this is a great way to get it.
    7 min
  • Web Forms in Ruby on Rails
    Building web forms in Rails was something that confused me when I was new to the framework. This is probably due to the fact that there are some methods that are a lot alike and there are a couple of ways of instantiating a form that do different things.
    The first way of building a form that is probably the most common is by using the ‘form_tag’ helper and the form helpers to build forms. Here’s an example.
    Pretty straightforward and it builds a standard login form. I’d get confused because there are also helpers that correspond to ‘label_tag’, ‘text_field_tag’, and ‘password_field_tag’ that do something very similar.
    Here’s a user signup form that use these similar tags:
    You’ll notice that these helpers use two parameters to build the form’s elements. It effectively scopes or namespaces those form parameters. They’ll be named “user[username]”, etc.
    If you’ve gotten that much, then ‘form_for’ won’t be too much of stretch. ‘form_for’ takes a model object as a parameter and binds the form to that object. It does the namespacing implicitly, which means that ‘label’ and ‘text_field’, etc don’t need two parameters to name the element. Just one.
    So, you’ll notice that the ‘form_for’ passes a parameter to the block. That parameter is a FormBuilder that contains the object, scopes the elements, and sets their values.
    Finally, go sign up for the Rails course at http://railscoach.com/ruby-on-rails-courses/.
    8 min
  • Polymorphic Associations
    Rails has the concept of Polymorphic associations, which are associations that can be of different data types. For example, let’s say we have a Comment model. A comment in your app can be on a post or a page. Rather than creating a PostComment model and a PageComment model, you can set up your Comment model to have a polymorphic association to a Page or a Post.
    Generally people call these associations “something-able”. In this case, it would be commentable.
    Here’s a quick code sample:
    class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true
    end
    class Page < ActiveRecord::Base has_many :comments, :as => :commentable
    end
    class Post < ActiveRecord::Base has_many :comments, :as => :commentable
    end
    The only other thing you need to know is the database structure. On the database, you need two columns. A [polymorphic-association-name]_type string column and [polymorphic-association-name]_id integer column. In this case, it would be “commentable_type” and “commentable_id”.
    10 min
  • Model Associations
    ActiveRecord models are based upon tables in relational databases. This, of course, means that they can be relational. Models can associate in three main ways: one to many, one to one, and many to many.
    One to many is usually achieved by calling has_many on the model representing the “one” to state that it “has many” of its counterparts. The model that represents the “many” calls
    belongs_to . Here’s an example:
    class User < ActiveRecord::Base
    has_many :posts
    end
    class Post < ActiveRecord::Base
    belongs_to :user
    end
    In addition, the model that represents the “many” needs a reference column or foreign key for the “one”. In this case, the posts table would have a user_id column.
    One to one works the same way one to many works except it uses has_one instead of has_many.
    Many to many is implemented in one of two different ways. The first--and generally default--way of doing this is has_and_belongs_to_many. As you can imagine, this is used just like has_many or belongs_to except you call it in both models.
    class Tag < ActiveRecord::Base
    has_and_belongs_to_many :posts
    end
    class Post < ActiveRecord::Base
    has_and_belongs_to_many :tags
    end
    11 min
  • Rails Controllers: Before, After, and Around Filters
    In your Rails controllers you have filters you can place on incoming requests, outgoing responses, or wrap around your actions.
    Before filters are run on requests before the request gets to the controller’s action. It can return a response itself and completely bypass the action.
    The most common use of before filters is validating a user’s authentication before granting them access to the action designated to handle their request. I’ve also seen them used to load a resource from the database, check permissions on a resource, or manage redirects under other circumstances.
    After filters are run after the action completes. It can modify the response. Most of the time if something is done in an after filter, it can be done in the action itself, but if there is some logic to be run after running any of a set of actions, then an after filter is a good place to do it.
    Generally, I’ve seen after and around filters used for logging.
    Around filters may have logic before and after the action being run. It simply yields to the action in whatever place is necessary. Note that it doesn’t need to yield to the action and may run without doing so like a before filter.
    You can use around filters for exception handling, setup and teardown, and a myriad of other cases.
    8 min
  • ActiveRecord Callbacks
    You can get a full list of the ActiveRecord callbacks here.
    Callbacks are a handy way of insuring specific behaviors on your models as well as managing the events that follow the callbacks.
    For example, a before_destroy callback can be called to destroy associated objects. (This is best done on the association with :dependent => :destroy, but it makes sense here too.)
    You can also stop the destroy process if you have dependent objects you can’t destroy by returning false.
    I’ve used ActiveRecord Callbacks to:
    Set default values
    Format specific fields (like phone numbers)
    Send emails when an object is updated or deleted
    Create child objects from comma delimited lists in a string
    Change an object’s state
    9 min
  • The DRY Principle
    According to The Pragmatic Programmer by Andy Hunt and Dave Thomas, "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
    Last week I talked about extending your Ruby on Rails application. This is because in many cases in order to avoid repeating your logic across multiple classes (models or controllers) you need another place to put your functionality.
    Mix-in modules, plugins, and single table inheritance all allow you to codify your knowledge into a single place depending on what you’re working with.
    The DRY principle is more than just a way to avoid having to update multiple files when something changes. Rather, it’s a way of assuring yourself that things are done in a consistent manner.
    It also helps you when you’re trying to find something in your application because there’s only one place where it can be found.
    8 min
  • Extending Ruby on Rails
    I’m going to be talking about the DRY principle next week. However, before I jump into that, I need to discuss how to extend Ruby on Rails so you know where you can put functionality to keep your application DRY.
    There are a couple of standard places people put code that isn’t a Model, View, Controller, or Helper:
    The ‘lib’ folder - This is sort of a “junk drawer” for your application. In Rails 3 your application does not load these files on its own. You can make it autoload by following the directions I found on StackOverflow.
    Rails Plugins - Rails Plugins are autoloaded by your Rails applications and can contain extensions to Models, Views, Controllers, Helpers, and to the app as a whole through Engines.
    Ruby Gems - Gems can do pretty much anything Plugins can do except they are not included in your application’s source. They are pulled in through Bundler.
    You can also add modules and classes to files within the app directory.
    10 min
  • Rails’ Component Libraries
    Rails is made up of several components that all have specific jobs in making your Rails application work. Here’s a quick list of what they are and what they do.
    ActionMailer - The basis for mailers. This is the library that allows you to format and send emails from your rails application
    ActionPack - The components that parse, delegate, and render responses for requests.
    ActionDispatch - Parses HTTP requests and sends the requests to controllers.
    ActionController - Basis for Controllers -Takes requests and request parameters and gathers data to render a response.
    ActionView - Basis for Views. Determines which template to use and builds the response to the HTTP request from the templates based on data provided by the Controller.
    ActiveModel - Defines an interface on non-ActiveRecord classes that helps the behave like ActiveRecord models.
    ActiveRecord - Basis for Models. Manages the connection between the Rails application and a SQL database. Provides means of querying database to manage and find records.
    ActiveResource - Allows the developer to access network REST resources in a simple way.
    ActiveSupport - A collection of extensions to the Ruby programming language that can be used in your Ruby on Rails application.
    You can read in more detail what these libraries are about and what they do on the Ruby on Rails github page.
    10 min
  • Debugging
    We talked quite a bit today about debugging tools in the Ruby Rogues podcast. I recorded this before that episode. Here's a brief introduction on how to use debuggers to find problems in your Rails code.
    The basic idea is that your set a breakpoint in your application, which causes the application to stop processing and allow you to access the application's state and step through the methods being called in order to find the cause of your problem.
    With the Ruby Debug library, all you need to do is require 'ruby-debug' and call 'debugger' where you want the application to stop.
    9 min

About Rails Coach

From the publisher's feed

Your Playbook for Ruby on Rails

More shows like Rails Coach

Teach Me To Code » Screencasts by Charles Max Wood

Teach Me To Code » Screencasts

11 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

45 Listeners

The Freelancers' Show by Charles M Wood

The Freelancers' Show

23 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

234 Listeners

iPhreaks by Charles M Wood

iPhreaks

17 Listeners

React Native Radio by Jamon Holmgren, Robin Heinze, Mazen Chami

React Native Radio

67 Listeners

Adventures in Angular by Charles M Wood

Adventures in Angular

15 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

62 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

21 Listeners

My JavaScript Story by Charles M Wood

My JavaScript Story

4 Listeners