如何在track_activity中包含id?

时间:2015-06-06 05:17:43

标签: ruby-on-rails ruby model-view-controller feed

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

  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

跟踪活动,以便它可以在Feed中显示。我还希望将valu_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

1 个答案:

答案 0 :(得分:2)

由于R_O_R指出trackable_id代表valu_id,这意味着我可以取出所有其他ID,因为它具有多态性。