2008年8月4日 星期一

ActiveRecord::Base

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001343


  Company.find(:first, :conditions => [
"id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
{ :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
])

  Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
Student.find(:all, :conditions => params[:student]);
Student.find(:all, :conditions => { :grade => 9..12 })
Student.find(:all, :conditions => { :grade => [9,11,12] })


class Song < ActiveRecord::Base
# Uses an integer of seconds to hold the length of the song
def length=(minutes)
write_attribute(:length, minutes.to_i * 60)
end

def length
read_attribute(:length) / 60
end
end


# Now 'Bob' exist and is an 'admin'
User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }


class User < ActiveRecord::Base
serialize :preferences
end
user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }


class User < ActiveRecord::Base
serialize :preferences, Hash
end
user = User.create(:preferences => %w( one two three ))
User.find(user.id).preferences # raises SerializationTypeMismatch


User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
u.is_admin = false
end


# Delete multiple objects
todos = [1,2,3]
Todo.delete(todos)

Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)

Person.exists?(:name => "David")
Person.exists?(['name LIKE ?', "%#{query}%"])


Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
Person.find(:all, :offset => 10, :limit => 10)
Person.find(:all, :include => [ :account, :friends ])
Person.find(:all, :group => "category")

Person.transaction do
person = Person.find(1, :lock => true)
person.visits += 1
person.save!
end

Post.update_counters 5, :comment_count => -1, :action_count => 1

{ :name => "foo'bar", :group_id => 4 }
# => "name='foo''bar' and group_id= 4"
{ :status => nil, :group_id => [1,2,3] }
# => "status IS NULL and group_id IN (1,2,3)"
{ :age => 13..18 }
# => "age BETWEEN 13 AND 18"
{ 'other_records.id' => 7 }
# => "`other_records`.`id` = 7"

沒有留言: