Ruby on Rails中的ActiveRecord编程指南

所属分类: 脚本专栏 / ruby专题 阅读数: 721
收藏 0 赞 0 分享


    避免改动缺省的 ActiveRecord(表的名字、主键,等等),除非你有一个非常好的理由(像是不受你控制的数据库)。
    把宏风格的方法放在类别定义的前面(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

    当一个惯用的验证使用超过一次或验证是某个正则表达映射时,创建一个惯用的 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

    所有惯用的验证器应放在一个共享的 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

    当一个由 lambda 及参数定义的作用域变得过于复杂时,更好的方式是建一个作为同样用途的类别方法,并返回一个 ActiveRecord::Relation 对象。你也可以这么定义出更精简的作用域。

  class User < ActiveRecord::Base
   def self.with_orders
    joins(:orders).select('distinct(users.id)')
   end
  end

    注意 update_attribute 方法的行为。它不运行模型验证(不同于 update_attributes )并且可能把模型状态给搞砸。

    使用用户友好的网址。在网址显示具描述性的模型属性,而不只是 id 。
    有不止一种方法可以达成:

        覆写模型的 to_param 方法。这是 Rails 用来给对象建构网址的方法。缺省的实作会以字串形式返回该 id 的记录。它可被另一个具人类可读的属性覆写。

    class Person
     def to_param
      "#{id} #{name}".parameterize
     end
    end

    为了要转换成对网址友好 (URL-friendly)的数值,字串应当调用 parameterize 。 对象的 id 要放在开头,以便给 ActiveRecord 的 find 方法查找。
    * 使用此 friendly_id gem。它允许藉由某些具描述性的模型属性,而不是用 id 来创建人类可读的网址。

  Ruby
  class Person
  extend FriendlyId
  friendly_id :name, use: :slugged
  end

    查看 gem 文档获得更多关于使用的信息。

更多精彩内容其他人还在看

Rails link_to 详解

想学习rauks link_to的朋友可以参考下面的例子。
收藏 0 赞 0 分享

ruby 小脚本搞定CVS服务器更换后checkout下来的工程迁移

CVS换了新的服务器,原来的工程需要更改Server配置,这个东东手工做起来 可是个体力活,写了一个脚本分发下来。
收藏 0 赞 0 分享

Ruby 魔法 学习笔记之一

Ruby的许多动态特性,让Ruby具有很多魔法,这个魔法足以让你来定制你自己的语言DSL, Rails就是Ruby在Web的DSL.
收藏 0 赞 0 分享

Ruby self在不同环境的含义

Ruby的self在不同的环境中有不同的含义,这点和java的this不同,原因是java实际上只有一种环境--在class的实例方法定义中使用,代表访问这个方法参数自动传进的那个对象。
收藏 0 赞 0 分享

ruby 程序的执行顺序

ruby程序的执行是顺序执行的,他是从脚本的第一行执行到最后一行,但是实际执行顺序是
收藏 0 赞 0 分享

ruby on rails 代码技巧

对于rails的一些使用技巧的代码
收藏 0 赞 0 分享

ruby 标准类型总结

诠释分析了ruby的标准类型,学习ruby的朋友,需要了解和掌握的。
收藏 0 赞 0 分享

ruby 去掉文件里重复的行

以前合并后台字典时,有重复的都是用vbs去,最近又看了一天的ruby,想起来写一下,没想到代码如此精简
收藏 0 赞 0 分享

Ruby rails 页面跳转(render和redirect_to)

今天在做R.R.log的时候发现个问题,在修改密码的时候如果没有通过校验,没有显示校验错误的信息。
收藏 0 赞 0 分享

Ruby 取得指定月日期数的方法

取得指定月日期数的Ruby代码
收藏 0 赞 0 分享
查看更多