Ruby on rails 混合有一个,属于双向关联

Ruby on rails 混合有一个,属于双向关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,在下面的(虚构的)示例中,每个帖子都是由一个用户创建的。出于性能原因,我们需要“写下”用户的第一篇帖子。因此,模式如下所示: 我现在的问题是,如何用活动记录对此进行建模?以下是正确的吗 class User < ActiveRecord::Base belongs_to :first_post, :class_name => 'Post' has_many :posts end class Post < ActiveRecord::Base belongs_to

在下面的(虚构的)示例中,每个帖子都是由一个用户创建的。出于性能原因,我们需要“写下”用户的第一篇帖子。因此,模式如下所示:

我现在的问题是,如何用活动记录对此进行建模?以下是正确的吗

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
class用户'post'
有很多帖子吗
结束
类Post
在这种情况下,您不需要在
Post
类中使用这两个关联。您应该能够像这样获得您想要的行为:

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

class Post < ActiveRecord::Base
  belongs_to :user
end

可能您必须将您的
Post
模型中的
has one:user
更改为类似于
has one:owner,:class\u name=>“user”
。但是将此与
一起使用对我来说没有任何意义。
class User < ActiveRecord::Base
  has_many :posts

  def first_post
    Post.find(first_post_id)
  end
end