Activerecord相同模型之间的两种不同关联

时间:2014-12-07 07:05:17

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord many-to-many

我刚刚开始使用Ruby on Rails

我有一个模型用户

class User < ActiveRecord::Base
  has_many :posts
end

和模型Post

class Post < ActiveRecord::Base
  belongs_to :author, foreign_key: 'user_id', class_name: 'User'
end

我想让用户与其他用户分享帖子,但我真的迷失了,我尝试过多次与桌子共享和使用:通过,但我只是更加困惑,我可以真的用一只手,提前谢谢。

1 个答案:

答案 0 :(得分:0)

  • 第一个解决方案

如果您不需要有关共享帖子的更多信息(例如共享帖子,为什么等等...)

在用户模型中

class User < ActiveRecord::Base
  # created posts
  has_many :posts,
      :foreign_key => :user_id 
  # shared posts
  has_and_belongs_to_many :shared_posts
end

在Post模型中

class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
  has_and_belongs_to_many :viewers
end

移植

create_table :posts_users do |t|
   t.references :user
   t.references :post
end

第二个解决方案

如果您确实需要更多信息(共享时,用户可以发表评论,还是......)。您应该使用through

在用户模型中

class User < ActiveRecord::Base
  # created posts
  has_many :posts,
      :foreign_key => :user_id 
  # shared posts
  has_many :shares, 
      class_name: "Post"
  has_many :shared_posts,
      through: :shares
end

在Post模型中

class Post < ActiveRecord::Base
  belongs_to :author,
       class_name: 'User'
  # shared posts
  has_many :shares
  has_many :viewers,
       through: :shares
end

在分享模式中

class Share < ActiveRecord::Base
   belongs_to :user
   belongs_to :post
end

另见Choosing between has_many_and_belongs_to has_many through

相关问题