Search code examples
ruby-on-railsrubymodel-view-controllerfeed

How to include id with track_activity?


When a user creates a new valuation...

  def create
    @valuation = current_user.valuations.build(valuation_params)
    if @valuation.save
      track_activity @valuation # LOOK AT THIS LINE
      redirect_to @valuation, notice: 'Value was successfully created'
    end
  end

the activity is tracked so that it can show in the feed. I also want the valuation_id to be passed with it because right now it shows in the console: valuation_id: nil.

How can we do this?

Activity.find(5)
  Activity Load (0.2ms)  SELECT  "activities".* FROM "activities" WHERE "activities"."id" = ? LIMIT 1  [["id", 5]]
=> #<Activity:0x007fd537c19f30
 id: 5,
 habit_id: nil,
 quantified_id: nil,
 valuation_id: nil,
 goal_id: nil,
 user_id: 1,
 action: "create",
 trackable_id: 5,
 trackable_type: "Valuation", #Interestingly enough it states the name of it here even though the id is "nil"
 created_at: Sat, 06 Jun 2015 04:48:49 UTC +00:00,
 updated_at: Sat, 06 Jun 2015 04:48:49 UTC +00:00,

schema

  create_table "activities", force: true do |t|
    t.integer  "habit_id"
    t.integer  "quantified_id"
    t.integer  "valuation_id"
    t.integer  "goal_id"
    t.integer  "user_id"
    t.string   "action"
    t.string   "test"
    t.integer  "trackable_id"
    t.string   "trackable_type"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.integer  "likes"
  end

activity.rb

class Activity < ActiveRecord::Base
  self.per_page = 20
  belongs_to :user
  belongs_to :habit
  belongs_to :comment
  belongs_to :valuation
  belongs_to :quantified
  belongs_to :trackable, polymorphic: true

private

  def index
    Activity.order(created_at: :desc).index self
  end
end

activities_controller

class ActivitiesController < ApplicationController
    def index
        @activities = Activity.order("created_at desc").paginate(:page => params[:page])
    end

    def show
          redirect_to(:back)
    end

  def like
    @activity = Activity.find(params[:id])
    @activity_like = current_user.activity_likes.build(activity: @activity)
    if @activity_like.save
      @activity.increment!(:likes)
      flash[:success] = 'Thanks for liking!'
    else
      flash[:error] = 'Two many likes'
    end  
      redirect_to(:back)
  end
end

application_controller

  def track_activity(trackable, action = params[:action])
    current_user.activities.create! action: action, trackable: trackable
  end

Solution

  • As R_O_R pointed out trackable_id represents the valuation_id, which means I can take out all those other IDs since it's polymorphic.