Question

I am currently following Ryan Bates tutorial on activity feed from scratch.

**I added a originator_id to the database so that I can save the ID of the Owner who originated the post. But for some reason I can't get it to work.

My Database from Scratch

class CreateActivities < ActiveRecord::Migration
  def change
    create_table :activities do |t|
      t.belongs_to :user
      t.string :action
      t.belongs_to :trackable
      t.string :trackable_type

      ###I want to save the id corresponding to User who created the object 
      t.belongs_to :originator
      t.string :originator_type

      t.timestamps
    end
    add_index :activities, :user_id
    add_index :activities, :trackable_id
    add_index :activities, :originator_id
  end
end

Here is my Code

Models

class Activity < ActiveRecord::Base
  belongs_to :user
  belongs_to :trackable, polymorphic: true

  belongs_to : originator, polymorphic: true
  attr_accessible :action, :recipient, :trackable


  ###how can i set the originator_id value

  after_create :set_originator

    def set_originator
      self.originator.update_attribute(:originator, ???)
    end
end

Controllers

class ApplicationController < ActionController::Base

  ###sets the action and trackable values
  ###how can i the originator here. i keep getting an error saying undefined method
  ###why is it that rails recognizes trackable?

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

end

class LikesController < ApplicationController

  def create
   @like = Like.create(params[:like])
    @dailypost = @like.dailypost

    ###Used to call track activity method above
    track_activity @like
    respond_to do |format|
      format.js
      format.html { redirect_to :back }
    end
  end

end

Was it helpful?

Solution

Don't know how solid this answer will be as i add more models to the activities, but this worked for my likes model.

If anyone can provide another solution that will work with multiple models i would really appreciate it. :)

class ApplicationController < ActionController::Base

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

  def originator
    @like.dailypost.user
  end

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top