Ruby on rails rails 4有许多贯穿连接表合并
我有以下项目:Ruby on rails rails 4有许多贯穿连接表合并,ruby-on-rails,join,merge,has-many-through,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 这个助手工作得很好 我可以在此url:/projects/2/projsum中收集项目计划和当前
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
这个助手工作得很好
我可以在此url:/projects/2/projsum中收集项目计划和当前计划
计划项目:
名称数量
混凝土20吨
瓷砖52.1平方米
OSB 6件
当前项目:
名称数量
混凝土10吨
35平方米大厦
OSB 4件
沙22 m3
我的目标是:
合并项目:
名称数量
混凝土30t
瓷砖52.1平方米
OSB 10件
35平方米大厦
沙22 m3
如何合并当前项目和计划项目?您的示例不清楚。缺少模型,缺少模板。我鼓励你用最少的代码编写一个自我包含的要点,如果不是几个月前提出这个问题,它会显示你的问题。尽管如此,这还是出现在谷歌上,为什么不回答呢 此外,正如@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
您的项目模型有多个:项,通过::计划和多个:项,通过::当前。这怎么可能?这是可能的,并且运行良好。项目具有计划项,并且具有数量为的当前项。我想比较这两组。
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
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