วันเสาร์ที่ 26 มิถุนายน พ.ศ. 2553

define Attribute value

Define Attributes => list ของattribute ที่มีความสัมพันธ์กับตัวdata model class เนื่องจาก rails ช่วยในเรื่องของการ แปลงจาก data model concept ไปยัง table ใน database ซึ่งในเวลา runtime Active Record model จะืำทำการตรวจสอบ schema ซึ่งมี attribute ตามที่เราำได้ ทำการ migration ไว้
ซึี่้งเราอาจจะไม่จำเป็นต้อง 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
_before_type_cast.tr!('$,','')
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_ ซึ่งอาจจะได้ค่าออกมาเป็น อาร์เรย์หรือ single value ก็ได้
เช่น
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 ใช้ในยามจำเป็นเท่านั้น

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

แสดงความคิดเห็น