ruby-on-rails - 需要使用 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
解决方案
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
推荐阅读
- javascript - 1 个字母后,搜索字段将我踢出输入字段
- r - R Flexdashboard - 在标题中添加一个中断
- java - IB TWS API 在 EClientSocket 上调用 eDisconnect() 时出现 SocketException,发生在 java.io.DataInputStream.readInt(EClientSocket)
- mongodb - 为什么MongoDB支持事务?
- node.js - 节点js,当包含“include”和“where:array []”选项时,使用偏移量和限制对findAndCountAll进行Sequelize不起作用
- image - 有没有办法创建在点击或单击时翻转到另一侧(另一页)的图像?
- google-api - Google Calendar API 删除 410 错误是什么意思
- reactjs - 无法编译 React Native 应用程序
- r - 是否有任何函数可以让我将此列表转换为一组向量?
- java - 需要显式类路径的 Gradle 插件和不需要的 Gradle 插件有什么区别?