需要使用 rails 在 read_statuses table 中存储 post_id 和 user_id

Need to store the post_id and user_id in read_statuses table using rails

当我启动显示操作时,控制器想要将 post_id 和 user_id 存储到另一个 table.But 中,它只需要在第一次出现时存储 例如。 (如果用户 1 第一次打开 post 1,它会在数据库中创建一个条目,但不会在他第二次查看相同的 post 时创建) Post 控制器显示阳离子将是:

def show
  @post = @topic.posts.find(params[:id])
  @read_status= ReadStatus.create(user_id: current_user,post_id: @post.id)
end

Post 型号:

class Post < ApplicationRecord
  belongs_to :user
  has_many :read_statuses
  has_many :users,through: :read_statuses
end

用户模型:

class User < ApplicationRecord
  has_many :posts
  has_many :read_statuses
  has_many :posts, through: :read_statuses
end

读取状态模型:

class ReadStatus < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

将实例方法 mark_read_by_user 添加到您的模型 Post 并在其中使用 first_or_create 仅在关联记录不存在时才创建关联记录。

class Post < ApplicationRecord
  def mark_read_by_user(user)
    self.read_statuses.where(post_id: id, user_id: user.id).first_or_create
  end
end

在控制器中:

def show
  @post = @topic.posts.find(params[:id])
  @read_status = @post.mark_read_by_user(current_user)
end