每个帖子都有一个用户视图,每个用户视图都有很多用户。我想要一个单一的多对多有一个简单的.add()
和.remove()
函数像django。如何将current_user
置于视图的多对多关系中?
我找到了这个:
@post.userview.users << current_user
但它会带来一些SQL错误。它建议我添加一个post_id:
ERROR: column userviews.post_id does not exist
LINE 1: SELECT "userviews".* FROM "userviews" WHERE "userviews"."po...
^
HINT: Perhaps you meant to reference the column "userviews.posts_id".
答案之后,现在的错误是:
can't write unknown attribute `userview_id`
因为我稍微改变了迁移,所以userview引用了帖子和用户。发布has_one userview,has_many用户通过userview,userview has_many发布和has_many用户。
create_table "posts", force: :cascade do |t|
t.integer "userview_id"
t.bigint "userviews_id"
t.index ["userviews_id"], name: "index_posts_on_userviews_id"
end
create_table "userviews", force: :cascade do |t|
t.bigint "users_id"
t.bigint "posts_id"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["posts_id"], name: "index_userviews_on_posts_id"
t.index ["users_id"], name: "index_userviews_on_users_id"
end
class User < ActiveRecord::Base
has_many :viewed_posts, through: :userview, class_name: 'Post'
...
class Userview < ApplicationRecord
belongs_to :post
belongs_to :user
end
class Post < ApplicationRecord
belongs_to :user
has_many :userviews
has_many :viewers, through: :userview, class_name: 'User'
...
Could not find the source association(s) "viewer" or :viewers in model Userview. Try 'has_many :viewers, :through => :userviews, :source => <name>'. Is it one of post or user?
虽然,这是为unless @post.viewers.include?(current_user)
不确定我是否正确理解你想要实现的目标,但我会尝试修复你的联想。
要关联2个模型,您需要将外键存储在其中一个模型中。存储关键belongs_to
其他模型的模型。例如在posts
表中你有user_id
列,它意味着post belongs_to: user
和用户has_many :posts
(如果你需要一对一的关联,则为has_one :post
)。对于这种关联,您可以写:
user = User.first
post = Post.last
user.posts << post
如果您希望所有这些东西自动运行,您应该遵循有关命名的约定。外键应该是单数形式,如user_id
,而不是users_id
如果需要多对多关联,则需要创建一个存储两个外键的中间表。它可以使用简单的直接has_and_belongs_to_many
关联或更复杂的has_many through:
来完成
我认为在你的情况下它应该是:
class User < ActiveRecord::Base
has_many :userviews
# it is posts viewed by the user
# you need to specify class name because it differs from association name
has_many :viewed_posts, through: :userviews, class_name: 'Post'
# posts written by the user
has_many :posts
end
class Userview < ApplicationRecord
belongs_to :post
belongs_to :user
end
class Post < ApplicationRecord
belongs_to :user
has_many :userviews
has_many :viewers, through: :userviews, source: :user
end
这意味着你需要post_id
表中的user_id
和userviews
列以及user_id
表中的posts
。请删除无用的列并在迁移中添加所需的列。当你正确地设置它时,你将能够做到
@post.viewers << current_user
将current_user
添加到查看者列表。相应的用户视图实例自动创建
改变了has_many :viewers, through: :userviews, class_name: 'User'
到has_many :viewers, through: :userviews, source: :user