Ruby on rails 你经历过多次吗
我想对我的代码提出一个建议,因为我不能很好地使用has\u many槽关联 在我的例子中,用户可以标记为查看帖子。 他们可以评论文章,也可以写关于文章的笔记 这就是我所做的:Ruby on rails 你经历过多次吗,ruby-on-rails,activerecord,model,Ruby On Rails,Activerecord,Model,我想对我的代码提出一个建议,因为我不能很好地使用has\u many槽关联 在我的例子中,用户可以标记为查看帖子。 他们可以评论文章,也可以写关于文章的笔记 这就是我所做的: class User has_many :posts, through: post_views has_many :posts, through: comments has_many :posts, through: notes end class Post has_many :users, throu
class User
has_many :posts, through: post_views
has_many :posts, through: comments
has_many :posts, through: notes
end
class Post
has_many :users, through: post_views
has_many :users, through: comments
has_many :users, through: notes
end
class PostView
belongs_to: user
belongs_to: post
end
class Comment
belongs_to: user
belongs_to: post
end
class Note
belongs_to: user
belongs_to: post
end
可以吗?我能做些什么来获得更好的代码
编辑=在穆罕默德·阿布沙迪的回答之后
类用户
有很多:后视图
通过::post\u视图查看了许多帖子
has_many :comments
has_many :commented_posts, through: comments
has_many :notes
has_many :noted_posts, through: notes
end
class Post
has_many :post_views
has_many :viewer_users, through: post_views
has_many :comments
has_many :comments_users, through: comments
has_many :notes
has_many :notes_users, through: notes
end
class PostView
belongs_to: user
belongs_to: post
end
class Comment
belongs_to: user
belongs_to: post
end
class Note
belongs_to: user
belongs_to: post
end
行吗
谢谢
Lokhi您需要通过部分与连接模型建立关系,以便工作,因此
class User < ActiveRecord::Base
has_many :post_views
has_many :viewed_posts, through: :post_views
end
class PostView < ActiveRecord::Base
belongs_to :posts
belongs_to :users
end
class Post < ActiveRecord::Base
has_many :post_views
has_many :users, through: :post_views
end
class用户
另外两种型号也一样