Validating URLs in Rails

Ruby posted 11 months ago by christian

   1  validates_format_of :website, :with => URI::regexp(%w(http https))

via http://mbleigh.com/2009/02/18/quick-tip-rails-url-validation.html

Tagged rails, validation, active_record, url

Twitter type "followers, following database schema" for Rails/ActiveRecord

Ruby posted about 1 year ago by christian

Draft schema for Twitter type followers, following functionality:

   1  create_table "followers", :force => true do |t|
   2      t.integer "leader_id"
   3      t.integer "follower_id"
   4  end
   5  
   6  add_index "followers", ["leader_id", "follower_id"], :name => "index_followers_on_leader_id_and_follower_id", :unique => true

Just an idea, haven’t tested this yet.

Update: railscasts.com has published an article on how to use self-referential associations for this purpose:
http://railscasts.com/episodes/163-self-referential-association

Tagged twitter, follower, following, schema, active_record

How to update the ActiveRecord counter_cache magic column

SQL posted about 1 year ago by christian

You can use the model.update_counters method to update the counter_cache column. But if you have a million rows it be very fast.

So for large tables it’s best to do it with a query such as this:

   1  update categories, (select 
   2                        id as category_id, ifnull(count, 0) as count
   3                      from categories left join 
   4                        (select category_id, count(id) as count from products group by category_id) as count_table 
   5                      on 
   6                        categories.id = count_table.category_id) as count_table
   7  set 
   8    categories.products_count = count_table.count
   9  where
  10    categories.id = count_table.category_id

This query updates the count for all rows.

The code needs to be modified for your database design.

Tagged update, counter_cache, sql, rails, active_record