Easy Linking with Polymorphic Associations in Rails

Just a quick tip, this one! If you have a model that is polymorphic, say a comment model:

class Comment
  belongs_to :user 
  belongs_to :commentable, :polymorphic => true 

and you want to link to the item the comment relates to in the admin system, you can do this:

link_to comment.commentable.title, [:admin, comment.commentable]

Note this assumes all of your commentable models have a title attribute or method, and that you have used normal RESTful routes. The :admin symbol will namespace the link to /admin

Next post

Checking for a WiFi Connection in One Line

So if you have an app that requires a WiFi network connection in order to reliably synchronize some large-ish data set, you need to notify your user if the connection is not available. Apple provides the Reachability example app that demonstrates how to do this, and you can use the Reachablility class from that app in your own app:

Read More →