高级 Active Record:增强你的模型
1. 高级关联记录
在处理关联时,我们可以对关联命名进行重构。例如,在用户模型中,用户文章收到的评论可以被称为“回复”。以下是更新后的用户模型代码:
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
这里使用了 has_many :through 关联,它允许我们为关联赋予更友好的名称。 :source 选项用于定义关联的源名称,在这个例子中,回复就是文章的评论。
我们可以在控制台中测试这个关联:
>> user = User.first
=> #<User id: 1, email: "user@example.com", ...>
>> user.replies.empty?
=> true
>> article = user.articles.first
=> #<Article id: 8,
超级会员免费看
订阅专栏 解锁全文
22

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



