2009-03-24から1日間の記事一覧

Polymorphic Association

class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end class Article < ActiveRecord::Base has_many :comments, :as => :commentable end class Photo < ActiveRecord::Base has_many :comments, :as => :commentable #.…

Rails 2.3 : Nested Attributes / Nested Object Forms

accepts_nested_attributes_for / fields_for Nested attributes allow you to save attributes on associated records through the parent. automatic (and atomic) saving of a record together with its associated children, child-aware validations, a…

Rails 2.3 : Nested Transactions

transaction(:requires_new => true) If you want a transaction to be nested, you must explicitly add the :requires_new option. User.transaction do User.create(:username => 'Admin') User.transaction(:requires_new => true) do User.create(:user…

Rails 2.3 : Dynamic Scopes

scoped_by_ Order.scoped_by_customer_id(12) Order.scoped_by_customer_id(12).find(:all, :conditions => "status = 'open'") Order.scoped_by_customer_id(12).scoped_by_status("open") Ruby on Rails 2.3 Release Notes - 4.3 Dynamic Scopes

Rails 2.3 : Default Scopes

default_scope(options = {}) class Article < ActiveRecord::Base default_scope :order => 'created_at DESC' end Article.find(:all) #=> "SELECT * FROM `articles` ORDER BY created_at DESC" Article.with_exclusive_scope { find(:all) } #=> "SELECT…

Rails 2.3 : Batch Processing

find_in_batches / find_each Invoice.find_in_batches(:include => :invoice_lines) do |invoices| export.add_invoices(invoices) end User.find_each do |user| NewsLetter.weekly_deliver(user) end Ruby on Rails 2.3 Release Notes - 4.5 Batch Proces…

Rails 2.3 : Object#try

you can avoid nil-checking @person.try(:name) # @person ? @person.name : nil @people.try(:collect) {|p| p.name} Person.try(:find, 1) Product.find_by_price(4.95).try(:name) Ruby on Rails 2.3 Release Notes - 7.1 Object#try Class: Object Rail…

rescue_from

Rescue exceptions raised in controller actions. class ApplicationController < ActionController::Base rescue_from ActionController::RoutingError, :with => :route_not_found private def route_not_found(exception) render :text => exception.mes…

Rails 2.2 : Memoization

Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. extend ActiveSupport::Memoizable def full_name "#{first_name} #{last_name}" end memoize :full_name Ruby on Rails 2.2 Release Notes - 9.…

send_file

ファイルのダウンロード send_file '/path/to.jpeg', :type => 'image/jpeg' Module: ActionController::Streaming 画像やファイルをダウンロードさせる | メモ帳