has_many经过几次
has_many through several times
我想就我的代码提出建议,因为我不确定如何使用 has_many 槽关联。
在我的案例中,用户可以将视图标记为 Post。
他们可以评论 Posts,也可以写关于 Posts 的注释。
这是我所做的:
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
可以吗?我该怎么做才能获得更好的代码?
编辑 = Mohammad AbuShady 回答后
class 用户
has_many :post_views
has_many :viewed_posts, 通过: post_views
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
可以吗?
谢谢
洛基
您需要与连接模型建立关系才能使 through
部分正常工作,因此
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
其他两个模型也一样。
我想就我的代码提出建议,因为我不确定如何使用 has_many 槽关联。
在我的案例中,用户可以将视图标记为 Post。 他们可以评论 Posts,也可以写关于 Posts 的注释。
这是我所做的:
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
可以吗?我该怎么做才能获得更好的代码?
编辑 = Mohammad AbuShady 回答后 class 用户 has_many :post_views has_many :viewed_posts, 通过: post_views
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
可以吗?
谢谢
洛基
您需要与连接模型建立关系才能使 through
部分正常工作,因此
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
其他两个模型也一样。