【问题标题】:rails 4 has_many through join tables mergerails 4 has_many 通过连接表合并
【发布时间】:2014-04-15 20:49:13
【问题描述】:

我有项目:

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

我有计划和相同的模型,Currents(加入表格):

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

这个助手工作正常。

我可以在这个 url 中收集项目计划和当前的:/projects/2/projsum

计划项目:

名称数量

混凝土 20 吨

瓷砖 52.1 平方米

OSB 6 片

当前项目:

名称数量

混凝土 10 吨

块 35 平方米

OSB 4 片

沙子 22 立方米

我的目标是这样的结果:

组合项目:

名称数量

混凝土 30 吨

瓷砖 52.1 平方米

OSB 10 片

块 35 平方米

沙子 22 立方米

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

【问题讨论】:

  • 您的Project 模型有has_many :items, through: :planshas_many :items, through: :currents。这怎么可能?
  • 这是可能的并且工作正常。项目有计划的项目并且有数量的当前项目。我想比较这两组。

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


【解决方案1】:

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

另外,正如@Pavan 所提到的,拥有两个同名的关联并不好。我不明白你所说的“工作正常”是什么意思——这不好。您无法访问项目的计划项(@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多