Rails activity destroy record not working

2019-09-02 16:46发布

问题:

I'm having the strangest problem and I don't know how to fix it. My models have a polymorphic activity model associated with them that creates activities when a user creates a status, media, etc. Everything's working fine on my local build and even on my forked heroku app. But when I delete an item on my main app, it doesn't delete the corresponding activity. It only happens on the main app, both my local build and forked app delete the activity as expected. They're all using the same code. I don't know why it's not working.

statuses_controller.rb

class StatusesController < ApplicationController

    before_filter :find_status, only: [:edit, :update, :destroy]

    def create
        @status = current_member.statuses.new(params[:status])

        respond_to do |format|
            if @status.save
              @activity = current_member.create_activity(@status, 'created')
              format.html { redirect_to :back }
              format.json
              format.js
            else
              format.html { redirect_to profile_path(current_member), alert: 'Post wasn\'t created. Please try again and ensure image attchments are under 10Mbs.'  }
              format.json { render json: @status.errors, status: :unprocessable_entity }
              format.js
            end
        end
    end

    def destroy
        @activity = Activity.find_by_targetable_id(params[:id])
        if @activity
            @activity.destroy
        end
        @status.destroy

        respond_to do |format|
            format.html { redirect_to profile_path(current_member) }
            format.json { head :no_content }
        end
    end

    def find_status
        @status = current_member.statuses.find(params[:id])
    end 

end

member.rb

class Member < ActiveRecord::Base

    def create_activity(item, action)
        activity = activities.new
        activity.targetable = item
        activity.action = action 
        activity.save 
        activity
    end

end

Migration

class CreateActivities < ActiveRecord::Migration
    def change
        create_table :activities do |t|
            t.integer :member_id
            t.string :action

            t.integer :targetable_id
            t.string :targetable_type

            t.timestamps
        end

        add_index :activities, :member_id
        add_index :activities, [:targetable_id, :targetable_type]

    end
end

回答1:

I figured this out. I removed the before_filter :find_status on destroy and added this instead: @status = Status.find(params[:id]). Don't know why the previous way didn't work but this works on all builds.