Ruby on Rails - 模型
模型创建
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 } 使用 Authorship 连接模型选择所有书籍 @author.books
查看 Associations 了解更多详情。