gpt4 book ai didi

ruby-on-rails - 包含相关元素

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:59 25 4
gpt4 key购买 nike

我想将 includes 方法与我的帖子的相关元素一起使用

我的帖子可以与不同类型的元素相关联。我使用一个值 :cat 来知道某种元素是相关联的。

值的工作方式如下 (cat: (1 => Message, 2=>Question, 3=>Task, 4=>Event) 与 has_one 关联

示例:如果 post.cat == 3,我可以调用与方法 post.task 相关的任务

现在,我想用方法 include 优化我的 Post/Index 的 SQL 请求。但暂时不起作用。你能帮我找出我的代码错误吗?

后 Controller :

def index
@posts = current_user.posts
@posts.each do |post|
if post.cat == 3
@task = post.task.includes(:users)
elsif post.cat == 4
@event = post.event.includes(:reminds)
end
end
end

错误:未定义的方法“包括”

编辑:

后模型:

class Post < ApplicationRecord
has_one :post_message, dependent: :destroy
has_one :question, dependent: :destroy
has_one :task, dependent: :destroy
has_one :event, dependent: :destroy
end

任务模型:

class Task < ApplicationRecord
belongs_to :post
has_many :users_task, dependent: :destroy
has_many :users, through: :users_task
end

最佳答案

为什么要使用 @posts.each ?

对我来说,最好的解决方案是找到定义的 cat 运行 includes 方法的所有帖子。在你的情况下,它会是这样的:

@posts.where(cat: 1).includes(:message)
@posts.where(cat: 2).includes(:question)
@posts.where(cat: 3).includes(task: :users)
@posts.where(cat: 4).includes(event: :reminds)

关于ruby-on-rails - 包含相关元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com