保存originator_id,来自Scratch的活动源

时间:2014-03-06 17:32:27

标签: ruby-on-rails ruby feed public-activity

我目前正在activity feed from scratch关注Ryan Bates教程。

**我在数据库中添加了一个originator_id,以便我可以保存发起帖子的所有者的ID。但由于某种原因,我无法让它发挥作用。

我的数据库来自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

这是我的代码

模型

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

控制器

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

1 个答案:

答案 0 :(得分:0)

当我为活动添加更多模型时,不知道这个答案会有多扎实,但这适用于我的喜欢模型。

如果任何人都可以提供可与多种模型配合使用的其他解决方案,我将非常感激。 :)

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