首页 > 解决方案 > 需要使用 rails 将 post_id 和 user_id 存储在 read_statuses 表中

问题描述

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

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

岗位型号:

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

标签: ruby-on-railsruby-on-rails-3

解决方案


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

推荐阅读