Question

I am trying to create an activity stream so my model looks like

class CreateFeeds < ActiveRecord::Migration
  def change
    create_table :feeds do |t|
      t.integer :item_id
      t.string :item_type
      t.integer :user_id

      t.timestamps
    end
  end
end

class Feed < ActiveRecord::Base
  belongs_to :user
  belongs_to :item, polymorphic: true
end

I have added this to my post controller

feed_item @post

and this to my application controller

def feed_item(item, action = params[:action])
   current_user.feeds.create! action: action, item: item
end

I am displaying my post content like

= feed.item.text

my problem is when I call

= link_to "delete", feed.item, method: :delete

I delete the feed item but the reference to the item remain in the database and I get

error: missing template "delete"

unless I add if present?

How can I this reference to an item?

Was it helpful?

Solution

Your code is simply deleting the item, with no impact on the feed. I think you need to either:

  • Explicitly clear the item_type and item_id references in feed (e.g. by implementing a remove_item method in your Feed controller and model), or
  • If your domain would allow for it, change your belongs_to association to a has_one association, with corresponding changes to your database. In that case, deleting the item wouldn't require any changes to the associated feed.

As an aside, it's unusual to keep your migration in with your model definition. The migration should really be in a separate file.

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