rails 4 has_many通过连接表合并

时间:2014-04-15 20:49:13

标签: ruby-on-rails join merge has-many-through

我有项目:

class Project < ActiveRecord::Base
 has_many :plans, dependent: :destroy
 has_many :items, through: :plans

 has_many :currents, dependent: :destroy
 has_many :items, through: :currents
end

我有计划和相同的模型,电流(连接表):

class Plan < ActiveRecord::Base
 belongs_to :project
 belongs_to :item
 validates :quantity, presence: :true
end

我的projects_helper.rb包含:

def filtered_currents
 tank = Current.where(:project_id => @project.id)
 currents = tank.group("item_id")
 @filtered_currents = currents.select("item_id, sum(quantity) as total_quantity")
end

def filtered_plans
 storage = Plan.where(:project_id => @project.id)
 plans = storage.group("item_id")
 @filtered_plans = plans.select("item_id, sum(quantity) as total_quantity")
end

这个助手工作正常。

我可以在此网址收集项目计划和当前内容:/ projects / 2 / projsum

计划项目:

名称数量

具体20吨

瓷砖52.1 m2

OSB 6件

当前项目:

名称数量

具体10 t

块35 m2

OSB 4件

沙子22 m3

我的目标是这样的结果:

合并项目:

名称数量

具体30 t

瓷砖52.1 m2

OSB 10件

块35 m2

沙子22 m3

如何合并当前项目和计划项目?

1 个答案:

答案 0 :(得分:0)

你的例子不清楚。缺少模型,缺少模板。我鼓励你写一个含有最少量代码的自包含的要点,如果问到这个问题已经过了几个月,就会显示你的问题like Rails core recommends。不过,这出现在Google上,为什么不回答?

另外,正如@Pavan所提到的,有两个同名的关联并不好。我不明白你的意思&#34;工作正常&#34; - 它不好。您无法访问项目的计划项目(@project.items始终使用第二项)。

话虽如此,这就是我要做的事情:

class Project < ActiveRecord::Base
  has_many :plans, dependent: :destroy
  has_many :planned_items,
    through: :plans,
    source: :item

  has_many :currents, dependent: :destroy
  has_many :current_items,
    through: :currents,
    source: :item

  def items
    Item
      .joins(:plans, :currents)
      .where('plans.project_id = ? OR currents.project_id = ?', id, id)
      .uniq
  end
end