Tagged as rails

edit delete favorite
Posted by kylejginavan on Nov 01, 2007
This two little nuggets does the inverse of column.human_name and gives you the data type if you have the human name and not column object.
def self.get_column_name(column_name)
  return column_name.downcase.gsub(/ /,'_')
end 
  
def self.get_column_type(column_name)
  for column in Object.content_columns 
    if column.name == get_column_name(column_name)
      return column.klass
    end
  end
end
 
edit delete favorite
Posted by eric on Nov 01, 2007
with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation. with_scope lets us extract that parameter.
# Notice we have to pass in the 'user_id' on both the find and create method.
def create_avoid_dups
  user_id = current_user.id

  # Find all user's posts
  user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])

  # Do some logic ...

  # then create new
  @post = Post.create(:body => params[:body], :user_id => user_id)
end

# with_scope lets us extract that parameter:
def create_avoid_dups
  Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
                  :create => {:user_id => current_user.id}) do

    # Find all user's posts
    # No longer need user_id condition since we're in scope
    user_posts = Post.find(:all)

    # Do some logic ...

    # then create new, without specifying user_id
    @post = Post.create(:body => params[:body])
  end
end
 
edit delete favorite
Posted by eric on Nov 01, 2007
Rather than ugly urls like http://snipsnipe.com/snip/view/13 [snipsnipe.com], use the following hack to make more meaningful urls like http://snipsnipe.com/snip/view/13-pretty-urls-in-rails [snipsnipe.com].
class Code < ActiveRecord::Base
  def to_param
    "#{id}-#{full_name.gsub(/[^a-z1-9]+/i, '-')[0,40]}"
  end
end
 
edit delete favorite
Posted by eric on Apr 27, 2009
These are two Rails helpers that could be very useful when injecting new instance methods in a class. underscore and classify
'MyClassName'.underscore => my_class_name
cool_articles".classify => CoolArticles
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Tags
Spacer