【问题标题】:How do I modify a record in a different model如何修改不同模型中的记录
【发布时间】: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_activitiesdurations 的总和?如果您编辑您的问题以包含一些示例数据和您的预期结果,这将很有帮助。

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller model


【解决方案1】:

如果我理解正确,您正在尝试获取一个人的所有 house_activitiesdurations 的总和。您可以使用 Rails 的ActiveRecord::Calculations#sum 方法直接从数据库中获取:

person = Person.find(123)
puts person.house_activities.sum(:duration)
# => 500

当然,您也可以为此创建一个辅助方法:

class Person < ActiveRecord::Base
  # ...

  def total_activities_duration
    house_activities.sum(:duration)
  end
end

person = Person.find(123)
puts person.total_activities_duration
# => 500

我建议不要将此总和存储在数据库中,因为这样您必须确保其一致性(例如,每次创建、编辑或删除作业时,您都必须确保关联的 Person 更新为新的总和)。您可能会认为每次重新计算总和会降低您的应用程序的速度,并且可能在将来的某个时间当您拥有数千条记录时,但除非出现实际性能问题,否则无需对此进行优化。

【讨论】:

  • 哇,这比我想象的要容易得多。感谢您的帮助和建议!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多