[英]How to access join table attributes (has_many :through) from association
I'm trying to create records list with the attributes of the associated records. 我正在尝试使用相关记录的属性创建记录列表。 Get Task
goal
Attribute inherit \\ replace Power
- goal
Attribute 获取Task
goal
属性继承\\替换Power
goal
属性
if we have: 如果我们有:
@tasks = user.tasks
when we render the view 当我们渲染视图时
<%= render @tasks %>
Everything is fine, we can just use <%= task.goal %>
in the partial and all working, but if we have user.super_tasks
how to override goal in the partial? 一切都很好,我们只能在部分应用中使用<%= task.goal %>
,但如果可以使用user.super_tasks
如何在部分应用中覆盖目标?
The first thing that comes to mind is to make in the _task.htm.erbl
首先想到的是在_task.htm.erbl
<%= goal = if @super_tasks then task.powers.find_by(user_id: current_user).goal else task.goal end %>
It's kind of make it, but this ok if you have 3 records, with 15 it will make 15 request to db to find the join table each time. 有点类似,但是如果您有3条记录,就可以了,如果有15条记录,每次都会有15条请求db查找连接表。
Just added the tables to make it more clear: 刚刚添加了表格以使其更加清晰:
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
But if user have power they have more responsibilities, its not the first time that I stuck on that problem, for sure there is other way to make this work without calling the db each time, as it sadly common problem. 但是,如果用户有权力,他们将承担更多责任,这不是我第一次遇到该问题,请确保还有其他方法可以使这项工作无需每次都调用db,这是可悲的常见问题。
Ok maybe it not the best solution, but it works and answers the question: 好的,也许这不是最好的解决方案,但它可以解决以下问题:
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
The weak point if this code is, if we say there is no task_id
to order \\ adjust the power
or if the number power_tasks
does not match the tasks. 该代码的弱点在于,如果我们说没有task_id
来订购\\调整power
或者如果power_tasks
的数量与任务不匹配。 But for my case it worked perfectly. 但是对于我来说,它运行得很好。
If you want to added other param, that not exist on normal Task
, but exist on Power
table and you want to added it to tasks
also, then in the model we can: 如果要添加其他参数,这些参数在普通Task
上不存在,但在Power
表上存在,并且您也想将其添加到tasks
,那么在模型中,我们可以:
class Task < ActiveRecord::Base
attr_accessor :cookies
task.cookies = power_tasks[i].cookies
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.