Search code examples
ruby-on-railspolymorphic-associations

How to delete a record in the polymorphic association in rails?


I have been following a polymorphic association example at this website https://www.richonrails.com/articles/polymorphic-associations-in-rails#comments

unfortunately, the author did not provide a example of how to delete a interaction under either people model or business model.

I have interactions_controller.rb

def destroy
  @context = context
  @interaction = @context.interactions.find(params[:id])
  @interaction.destroy
end

in routes.rb

resources :business do
  resources :interaction
end

in businesses/1, show.html.erb, it has a list all interactions.

<% link_to 'delete', business_interaction_path([@business, interaction]), method: :delete, data: {confirm: 'Are you sure?'} %>

I tried to use this to delete an individual interaction, the error message told me that it could find the business.id number, but cannot find interaction.id number.

This is both polymorphic association and nested resources so I got confused.

Can you tell me what I did wrong? Please you must understand this tutorial first before answering? Thanks!


Solution

  • <% link_to 'delete', business_interaction_path(@business, interaction), method: :delete, data: {confirm: 'Are you sure?'} %>
    
    
    def destroy
      @context = context
      @interaction = @context.interactions.find(params[:id])
      @interaction.destroy
      redirect_to context_url(context)
    end
    

    I forgot to redirect_to correct page after deleting. This is why it keeps giving me a error message.