- Ruby on Rails 教程
- Ruby on Rails - 主页
- Ruby on Rails - 简介
- Ruby on Rails - 安装
- Ruby on Rails - 框架
- Ruby on Rails - 目录结构
- Ruby on Rails - 示例
- Ruby on Rails - 数据库设置
- Ruby on Rails - 活动记录
- Ruby on Rails - 迁移
- Ruby on Rails - 控制器
- Ruby on Rails - 路由
- Ruby on Rails - 视图
- Ruby on Rails - 布局
- Ruby on Rails - 脚手架
- Ruby on Rails - AJAX
- Ruby on Rails - 文件上传
- Ruby on Rails - 发送电子邮件
- Ruby on Rails 资源
- Ruby on Rails - 引用指南
- Ruby on Rails - 快速指南
- Ruby on Rails - 资源
- Ruby on Rails - 讨论
- Ruby 教程
- Ruby 教程
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、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 # 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
检查 关联 以了解更多详情。
rails-references-guide.htm
广告