避免改动缺省的 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]+)@(("htmlcode">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 文档获得更多关于使用的信息。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 群星.1996-各自各精彩【上华】【WAV+CUE】
- 《终极幸运之塔》评测:藏在童年回忆里爬塔佳作
- 《战神5》PC版评测:轻推W缓慢前行
- 《阿瑞亚之旅》评测:更适合佛系玩家体质的跑团
- 黑神话悟空浮屠界紫门怎么开 浮屠界紫门打开方法介绍
- 黑神话悟空龟泪怎么获得 黑神话悟空龟泪获得方法介绍
- 黑神话悟空怎么获得还魂丹 黑神话悟空还魂丹获取方法一览
- HiFi顶级人声天碟《试音齐秦》wav
- 张敬轩.2012-WhyNot(EP)【环球】【WAV+CUE】
- 张小英1988-情愁[新加坡复黑版][WAV+CUE]
- 游民金币礼品补货啦 Steam充值卡等你兑换!
- 《暗喻幻想:ReFantazio》M站均分94分 近年最好的RPG游戏之一
- 今年第一项诺贝尔奖揭幕 生理学或医学奖揭晓
- 《梁静茹 华语乐坛情歌天后 爱久见人心》[WAV/分轨][360MB]
- 《田震 绝版珍藏 依然在飞》[WAV+CUE][600MB]