国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Ruby on Rails中的ActiveRecord編程指南

2019-10-26 19:28:16
字體:
供稿:網(wǎng)友


    避免改動缺省的 ActiveRecord(表的名字、主鍵,等等),除非你有一個非常好的理由(像是不受你控制的數(shù)據(jù)庫)。
    把宏風(fēng)格的方法放在類別定義的前面(has_many, validates, 等等)。

    偏好 has_many :through 勝于 has_and_belongs_to_many。 使用 has_many :through 允許在 join 模型有附加的屬性及驗證

   

 # 使用 has_and_belongs_to_many  class User < ActiveRecord::Base   has_and_belongs_to_many :groups  end  class Group < ActiveRecord::Base   has_and_belongs_to_many :users  end  # 偏好方式 - using has_many :through  class User < ActiveRecord::Base   has_many :memberships   has_many :groups, through: :memberships  end  class Membership < ActiveRecord::Base   belongs_to :user   belongs_to :group  end  class Group < ActiveRecord::Base   has_many :memberships   has_many :users, through: :memberships  end

    使用新的 "sexy" validation。

    當(dāng)一個慣用的驗證使用超過一次或驗證是某個正則表達(dá)映射時,創(chuàng)建一個慣用的 validator 文件。

  # 差  class Person   validates :email, format: { with: /^([^@/s]+)@((?:[-a-z0-9]+/.)+[a-z]{2,})$/i }  end  # 好  class EmailValidator < ActiveModel::EachValidator   def validate_each(record, attribute, value)    record.errors[attribute] << (options[:message] || 'is not a valid email') unless value =~ /^([^@/s]+)@((?:[-a-z0-9]+/.)+[a-z]{2,})$/i   end  end  class Person   validates :email, email: true  end

    所有慣用的驗證器應(yīng)放在一個共享的 gem 。

    自由地使用命名的作用域(scope)。

   

 class User < ActiveRecord::Base   scope :active, -> { where(active: true) }   scope :inactive, -> { where(active: false) }   scope :with_orders, -> { joins(:orders).select('distinct(users.id)') }  end

    將命名的作用域包在 lambda 里來惰性地初始化。

 

  # 差勁  class User < ActiveRecord::Base   scope :active, where(active: true)   scope :inactive, where(active: false)   scope :with_orders, joins(:orders).select('distinct(users.id)')  end  # 好  class User < ActiveRecord::Base   scope :active, -> { where(active: true) }   scope :inactive, -> { where(active: false) }   scope :with_orders, -> { joins(:orders).select('distinct(users.id)') }  end

    當(dāng)一個由 lambda 及參數(shù)定義的作用域變得過于復(fù)雜時,更好的方式是建一個作為同樣用途的類別方法,并返回一個 ActiveRecord::Relation 對象。你也可以這么定義出更精簡的作用域。

  class User < ActiveRecord::Base   def self.with_orders    joins(:orders).select('distinct(users.id)')   end  end            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 嵊州市| 长治县| 扶绥县| 西林县| 温泉县| 佛教| 绥德县| 孟州市| 济阳县| 农安县| 陇南市| 仙桃市| 中阳县| 本溪| 璧山县| 昌黎县| 南漳县| 裕民县| 绥滨县| 民乐县| 乌海市| 吉林市| 台前县| 宁远县| 台江县| 伊吾县| 靖州| 阜新| 开阳县| 财经| 巴中市| 泸定县| 绥江县| 郸城县| 铜鼓县| 河津市| 灵山县| 会昌县| 疏附县| 鄂托克旗| 元阳县|