如何列出用户可用的所有任务?

How can I list all tasks that are available for a user?

我正在尝试查询用户尚未完成的所有任务。

我创建了一个名为 state 的模型

class State < ActiveRecord::Base
  as_enum :value, %i{available inprogress completed}
  belongs_to :user
  belongs_to :task
end

class 用户和 class 任务与 class 状态有 has_many 关系。

我已经尝试这样做,并且最终得到了一个数组,如下所示:

@tasks = []
current_user.states.where(value_cd: 0).each do |task|
      @tasks << state.task
end

我怎样才能通过查询做到这一点?

我的希望是实现类似这样的东西:

Tasks.where(state.value: :available && state.user_id == current_user.id)

感谢任何帮助!

使用专用范围更新您的 User 模型:

has_many :available_tasks, -> { where('state.id' => 0) }, through: :state

并使用:

current_user.tasks

或使用:

Tasks.joins(:state).where(
  'state.value' => 0,
  'state.user_id' => current_user.id)

目前无法测试,但我相信你想使用includes。 像这样的东西应该可以工作:

tasks = Task.includes(:states).where(states: { value: :available, user_id: current_user.id})

您还可以阅读有关指定条件的更多信息here

但如果我没记错的话,您也可以通过这种方式获取用户尚未完成的所有任务:

current_user.tasks.map(&:states).map(&:available)

- engineersmnky 说我错了。

class Task
  has_many :states
end

Task.joins(:states).where(states: {user_id: current_user.id, value: :available})
Task.joins(:states).where.not(states: {value: :completed})
    .where(states: {user_id: current_user.id})

此方法首先确定您想要的结果是任务的集合。所以你想查询任务模型来给你那个结果。

current_user.states 关联将允许您查询状态,但您需要将其链接到任务查询,因此链接关联不会让您到达想要的位置。