Ruby on Rails 2.1 - 模型
模型创建
Model.new # 创建一个新的空模型 Model.create( :field => 'value', :other_field => 42 ) # 使用传递的参数创建一个对象并保存它 Model.find_or_create_by_field( value ) # 搜索"field = value"的记录,如果未找到则创建 # 新记录 User.find_or_create_by_name_and_email( 'ramjoe', 'ram@example.com')
模型关系
有四种关联模型的方法 - has_one、has_many、belongs_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 # 选择该作者所属的所有书籍。 @author.authorships.collect { |a| a.book } selects all books by using the Authorship join model @author.books