如何从关联访问加入 table 属性 (has_many :through)

How to access join table attributes (has_many :through) from association

我正在尝试创建具有关联记录属性的记录列表。获取Taskgoal属性继承\替换Power-goal属性

如果我们有:

@tasks = user.tasks

当我们渲染视图时

<%= render @tasks %>

一切都很好,我们可以在部分和全部工作中使用 <%= task.goal %>,但是如果我们有 user.super_tasks 如何在部分中覆盖目标?

首先想到的是_task.htm.erbl

<%= goal = if @super_tasks then task.powers.find_by(user_id: current_user).goal else task.goal end %>

有点成功,但是如果你有 3 条记录就没问题,如果有 15 条记录,它将每次向数据库发出 15 次请求以查找连接 table。

刚刚添加了 tables 以使其更清楚:

class User < ActiveRecord::Base
   has_many :tasks
   has_many :powers
   has_many :super_tasks , through: :powers, source: :task
end

class Task < ActiveRecord::Base
   belongs_to :user
   has_many :powers
end

class Power < ActiveRecord::Base
   belongs_to :user
   belongs_to :tasks 
end

但是,如果用户拥有权力,他们将承担更多责任,这不是我第一次遇到这个问题,当然还有其他方法可以使这项工作无需每次都调用数据库,因为这是一个很常见的问题。

好吧,这可能不是最好的解决方案,但它有效并回答了问题:

tasks = user.tasks.order(:id)
power_tasks = user.powers.order(:task_id)

tasks.each_with_index do |task,i|
    task.goal = power_tasks[i].goal 
end

如果这个代码的弱点是,如果我们说没有task_id来订购\调整power或者如果数字power_tasks不匹配任务。 但就我而言,它工作得很好。

如果你想添加其他参数,它不存在于正常 Task,但存在于 Power table,你也想将它添加到 tasks ,那么在模型中我们可以:

class Task < ActiveRecord::Base
   attr_accessor :cookies

task.cookies = power_tasks[i].cookies