【发布时间】:2016-09-04 14:41:02
【问题描述】:
我是一名 Rails 初学者,正在编写一个简单的应用程序来训练语言和其他内容。
在我的应用中,我生成了三种不同的脚手架,一种用于People,一种用于House Activities,最后一种用于将它们链接在一起,称为Assignments强>。这是多对多的依赖情况。
所以我试图计算一个人必须花费在分配给他们的所有房屋活动上的总时间,并将其存储在 Person 的一个名为“time_allocated”的属性中。因此,如果我有两个活动分配给某人,它将返回这些活动的持续时间的总和。
搜索后发现创建一个具有三个依赖的属性是不行的,但是我不知道怎么做。
这些是模型和我尝试做的事情:
人物模型
class Person < ActiveRecord::Base
has_many :assignments, dependent: :destroy
has_many :house_activities, through: :assignments
extend FriendlyId
friendly_id :name, use: :slugged
end
房屋活动模型
class HouseActivity < ActiveRecord::Base
has_many :assignments, dependent: :destroy
has_many :people, through: :assignments
extend FriendlyId
friendly_id :name, use: :slugged
end
分配模型
class Assignment < ActiveRecord::Base
belongs_to :person
belongs_to :house_activity
def self.time_allocation #fulltime
Assignment.all.each do |assignment|
if (assignment.person.time_allocation.present?)
assignment.person.time_allocation += assignment.house_activity.duration
else
assignment.person.time_allocation = assignment.house_activity.duration
end
end
end
end
【问题讨论】:
-
澄清一下,你是在问如何获得一个人的所有
house_activities的durations 的总和?如果您编辑您的问题以包含一些示例数据和您的预期结果,这将很有帮助。
标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller model