混合has_one和belongs_to用于双向关联

时间:2014-07-16 08:45:05

标签: ruby-on-rails activerecord

在以下(虚构)示例中,每个帖子都是由一个用户创建的。出于性能原因,我们需要"记下"用户所做的第一篇文章。因此,架构如下所示:

ERD

我现在的问题是,如何使用Active Record建模?以下是否正确?

class User < ActiveRecord::Base
  belongs_to :first_post, :class_name => 'Post'
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_one :user      # has_many would be wrong, as a
                     # post can't be the first post of
                     # more than one user.
end

1 个答案:

答案 0 :(得分:1)

在这种情况下,您的Post课程中不需要这两个关联。你应该能够得到你想要的行为:

class User < ActiveRecord::Base
  has_many :posts
  belongs_to :first_post, :class_name => 'Post'
end

class Post < ActiveRecord::Base
  belongs_to :user
end

这是因为您的第二个关联只是has_many关联的一个特例。每个帖子已经user_id相关联;您不必为first_post案例添加额外的一个。

但是,鉴于你可能不想做任何事情,除了访问这个用户的第一篇文章(因此不需要the extra methods added by belongs_to),将它写成普通方法可能更清楚:

class User < ActiveRecord::Base
  has_many :posts

  def first_post
    Post.find(first_post_id)
  end
end