Ruby on Rails - โมเดล

การสร้างแบบจำลอง

Model.new   # creates a new empty model
Model.create( :field ⇒ 'value', :other_field ⇒ 42 )
# creates an object with the passed parameters and saves it

Model.find_or_create_by_field( value )  
# searches for a record where "field = value", creates
# a new record if not found

User.find_or_create_by_name_and_email( 'ramjoe', '[email protected]')

รุ่นสัมพันธ์

การเชื่อมโยงโมเดลมีสี่วิธี has_one, has_many, belong_to และ has_and_belongs_to_many สมมติว่าสี่เอนทิตีต่อไปนี้ -

def Order < ActiveRecord::Base
   has_many :line_items
   belongs_to :customer 
end

def LineItem < ActiveRecord::Base
   belongs_to :order
end

def Customer < ActiveRecord::Base
   has_many :orders
   has_one :address
end

def Address < ActiveRecord::Base
   belongs_to :customer
end

พิจารณาความสัมพันธ์ต่อไปนี้ -

def Category < ActiveRecord::Base 
   has_and_belongs_to_many :products
end

def Product < ActiveRecord::Base
   has_and_belongs_to_many :categories  
end

สมาคมเข้าร่วมรุ่น

พิจารณาความสัมพันธ์ต่อไปนี้ตอนนี้ สิ่งนี้แสดงให้เห็นว่าเราสามารถใช้การรวมในขณะที่กำหนดความสัมพันธ์ได้อย่างไร

class Author < ActiveRecord::Base
   has_many :authorships
   has_many :books, :through ⇒ :authorships
end

class Authorship < ActiveRecord::Base
   belongs_to :author
   belongs_to :book
end

class Book < ActiveRecord::Base
   has_one :authorship
end

@author = Author.find :first
# selects all books that the author's authorships belong to.

@author.authorships.collect { |a| a.book }
selects all books by using the Authorship join model
@author.books

ตรวจสอบการเชื่อมโยงสำหรับรายละเอียดเพิ่มเติม

รางอ้างอิง-guide.htm

Language