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
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