如何在 track_activity 中包含 id?

How to include id with track_activity?

当用户创建新估值时...

  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

activity 已被跟踪,以便它可以显示在提要中。我还希望 valuation_id 与它一起传递,因为现在它显示在控制台中:valuation_id: nil.

我们如何做到这一点?

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,

架构

  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

正如 R_O_R 指出的那样 trackable_id 代表 valuation_id,这意味着我可以取出所有其他 ID,因为它是多态的。