【问题标题】:How to access join table attributes (has_many :through) from association如何从关联中访问连接表属性(has_many :through)
【发布时间】:2017-06-10 23:23:58
【问题描述】:

我正在尝试使用关联记录的属性创建记录列表。获取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 条它每次都会向 db 发出 15 次请求以查找连接表。

只是添加了表格以使其更清晰:

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

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

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord has-many-through


【解决方案1】:

好吧,也许它不是最好的解决方案,但它可以解决问题:

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

【讨论】:

    猜你喜欢
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    相关资源
    最近更新 更多