Ruby on rails 如何在rails迁移中向两个不同的模型添加多个关联?

Ruby on rails 如何在rails迁移中向两个不同的模型添加多个关联?,ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord,rails-migrations,Ruby On Rails,Ruby On Rails 4,Activerecord,Rails Activerecord,Rails Migrations,我怎样才能做到这一点 class User < ActiveRecord::Base has_many :old_posts has_many :new_posts end 您应该指定条件,因为两者都引用相同的模型 提及它显式引用的模型,因为由于自定义关联名称,它默认情况下不会标识模型 更新代码如下 class User < ActiveRecord::Base has_many :old_posts, ->{where("created_at

我怎样才能做到这一点

class User < ActiveRecord::Base     
  has_many :old_posts
  has_many :new_posts
end
  • 您应该指定条件,因为两者都引用相同的模型

  • 提及它显式引用的模型,因为由于自定义关联名称,它默认情况下不会标识模型

更新代码如下

class User < ActiveRecord::Base
    has_many :old_posts, ->{where("created_at > ?", Time.now.end_of_day)}, class_name: 'Post', foreign_key: 'user_id'
    has_many :new_posts, ->{where("created_at < ?", Time.now.end_of_day)}, class_name: 'Post',foreign_key: 'user_id'
end
class用户{where(“created_at>?”,Time.now.end_of_day)},类名:'Post',外键:'user_id'
有很多新帖子,>{where(“created_at<?”,Time.now.end_of_day)},类名:'Post',外键:'user_id'
结束

当你调用旧邮件和新邮件时,你期待什么?我的意思是,我正在使用两个不同的模型“旧帖子”和“新帖子”,这些模型现在有不同的列。@Lollypop你是说不同的外键?不,它是完全不同的表和模型。@Lollypop为什么创建两个具有相同属性的模型?它们有不同的列和属性。
class User < ActiveRecord::Base
    has_many :old_posts, ->{where("created_at > ?", Time.now.end_of_day)}, class_name: 'Post', foreign_key: 'user_id'
    has_many :new_posts, ->{where("created_at < ?", Time.now.end_of_day)}, class_name: 'Post',foreign_key: 'user_id'
end