[英]How to access join table attributes (has_many :through) from association
我正在尝试使用相关记录的属性创建记录列表。 获取Task
goal
属性继承\\替换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条请求db查找连接表。
刚刚添加了表格以使其更加清晰:
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
但是,如果用户有权力,他们将承担更多责任,这不是我第一次遇到该问题,请确保还有其他方法可以使这项工作无需每次都调用db,这是可悲的常见问题。
好的,也许这不是最好的解决方案,但它可以解决以下问题:
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
表上存在,并且您也想将其添加到tasks
,那么在模型中,我们可以:
class Task < ActiveRecord::Base
attr_accessor :cookies
task.cookies = power_tasks[i].cookies
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.