高级 Active Record:模型增强技巧
1. 高级关联记录
在开发中,关联关系的命名和使用至关重要。例如,我们可以使用 has_many :through 声明来优化关联命名。以下是更新后的 User 模型代码:
class User < ActiveRecord::Base
has_one :profile
has_many :articles, -> {order('published_at DESC, title ASC')}, :dependent => :nullify
has_many :replies, :through => :articles, :source => :comments
end
在这个模型中,用户文章下收到的评论被命名为 replies 。 has_many :through 不仅让关联命名更友好, :source 选项还能定义关联的源名称。
我们可以在控制台中进行测试:
>> user = User.first
=> #<User id: 1, email: "user@example.com", ...>
>> user.replies.empty?
=> true
>> article = user.article
超级会员免费看
订阅专栏 解锁全文
22

被折叠的 条评论
为什么被折叠?



