ซึี่้งเราอาจจะไม่จำเป็นต้อง extend จาก ActionRecord::Base ก็ได้
Default Attribute Values
ให้ที่ data model ซึ่งบาง attribute นั้น จำเป็นต้อง มีค่าเริ่มต้น เช่น score อะไรประมาณนี้ ซึ่งเป็นในส่วนของ data model เช่น
class Person ActiveRecord::base
def position
@position or 'n/a'
end
end
def position
read_attribute(:position) or 'n/a'
end
def position=(txt)
write_attribute(:position,txt+".")
end
p=Person.create
....... Position=>nil
>>p.position
employee
Hash Notation
c=Client.create :name=>"benz"
c[:name]
Attributes method
client.attributes
จะให้ attribute ที่่มีการกำหนดไว้
Accessing and Manipulating Attribute ก่อนการ TypeCast
activeRecord connection adapter จะ fetch ผลลัพธ์ของ String แล้ว railsจะ convert เป็น datatype ขึ้นอยู่กับ type ใน database column เช่น integer -> Fixnum class
class Client /< ActiveRecord::Base
before_save :string_checking
def string_checking
end
end
จะทำการแทนที่เครื่องหมาย $กับ , ด้วย '' ก่อนที่จะมีการทำtype casting สำหรับ
Reloading method
c=Client.create :name="benz"
c.reload
c.new_record?
->false
c=Client.new(:name=>"benz")
c.new_record?
->true
Dynamic Attribute-Based finder
คือการquery ด้วยการใช้คำสั่ง find ซึ่งจะทำการ execute เมื่อมีการเรียก method ที่ได้มีการdefineเอาไว้แล้ว
find_by_
find_all_by_
เช่น
find(:first,["user_name=?"AND password=?,user_name,password])
find_by_user_name_and_password
find_or_initialize_by_
param="benz"
find(:all ,conditions=>["name like ?",param])
Custom SQL QUERY ใช้ในยามจำเป็นเท่านั้น

ไม่มีความคิดเห็น:
แสดงความคิดเห็น