创建公告并将其与周对象关联(如果尚不存在)

时间:2014-03-26 22:31:59

标签: ruby-on-rails ruby activerecord

我有一个名为Period的模型,它有一个名为start_date的列。我还有一个名为Announcement的模型,它属于PeriodPeriod has_many属于Announcements

当我创建Announcement时,我想将其与Period相关联,但我首先要检查是否存在与Period {{匹配的announcements记录1}}约会。如果created_at记录确实存在,只需将Period添加到period_id

如果没有,则创建Announcement记录并将其Period添加到ID

这是我到目前为止我的两个模型的代码

期间模型:

announcement

公告模式:

class Period < ActiveRecord::Base
  has_many :announcements

  def self.find_or_create(date)
    start_date = date.beginning_of_week
    where(start_date: start_date).first || create_through_related(date)
  end

  def self.create_from_related(date)
    start_date = date.beginning_of_week
    create! do |period|
      period.start_date = date.start_date
      period.duration = 7
    end
  end
end

1 个答案:

答案 0 :(得分:1)

A之前的过滤器?

class Announcement < ActiveRecord::Base
  belongs_to :period

  before_create :assoc_period

  private

    def assoc_period
      self.period = Period.find_or_create(self.created_at)
    end
end