Ryan Rebo
Ryan Rebo

Reputation: 1318

Auto-create Association Object?

I have a Track model with an integer attribute called rank. I'm updating the rank by specific actions: listens, downloads, purchases, ect. Ex: when a track is downloaded, in the track_controller I use track.increment!(:rank, by = 60)

I am thinking of creating an association model TrackRank so I can have a timestamp anytime a track's rank is updated (so I can do a rolling 3-week query of a track's rank for filtering and display purposes).

For every time a Tracks rank attr is updated, is there a way to auto-create an associated TrackRank object?

The ultimate goal: Be able query the top X amount of tracks based on rank count in the last 3 weeks.

Upvotes: 0

Views: 845

Answers (2)

pauloancheta
pauloancheta

Reputation: 359

You can update it on the controller

class TracksController < ApplicationController
  def update
    @track.update!
    TrackRank.create(@track)
  end
end

Upvotes: 0

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42789

You can add a conditional call back on the update of the track

class Track < ActiveRecord::Base
  # ignored associations and stuff
  after_update :create_track_rank, if: :rank_changed?

  # ignored methods

  private
  def create_track_rank
    track_ranks.create(data)
  end
end

Upvotes: 2

Related Questions