0

I have the following code which gives me an ActionView::Template::Error (undefined methodroster_path' for #<#:0x007fe34005c208>):`

While in the background it deletes the association player_roster (Has and belongs to many), but i want to delete it when i press the link.

The roster path is nested within a team, but the issue is regarding roster and players.

<%= form_for [@team, @roster] do |f| %>
    <% @players.each do |player| %>
      <%= player.gamertag %>
      <%= link_to "Delete", player.rosters.delete(@roster) %>
    <% end %>
<% end %>

:Update

Player.rb

class Player < ActiveRecord::Base
    has_and_belongs_to_many :rosters
    belongs_to :country

    mount_uploader :picture, PictureUploader
end

Roster.rb

class Roster < ActiveRecord::Base
    has_and_belongs_to_many :players
    has_many :placements

    belongs_to :team, touch: true
end
Pierre
  • 1,114
  • 2
  • 10
  • 24
  • What are your relations like in your models? The way you'd get the deletion to occur is to use `dependent: :destroy`, but we don't know unless you post the model code :) – Richard Peck Nov 28 '13 at 09:30
  • Updated my question with both models :) – Pierre Nov 28 '13 at 16:46

1 Answers1

0

The way you are doing it now will call your delete when the page loads. You can't link to arbitrary Ruby code, you need to link to a route and controller action which will perform your logic.

<%= form_for [@team, @roster] do |f| %>
    <% @players.each do |player| %>
      <%= player.gamertag %>
      <%= link_to "Delete", player_roster_path(player, @roster), method: :delete %>
    <% end %>
<% end %>

This link will route to players/:id/rosters/:id with the DELETE HTTP action, which Rails will route to the destroy method.

class RostersController < ApplicationController

  def destroy
    @player = Player.find(params[:player_id])
    @roster = Roster.find(params[:id])
    @player.rosters.destroy(@roster)
    # redirect/render
  end

end

You also will need to setup player_roster_path as a route in config/routes.rb

resources :players do
  resources :rosters, only: [:destroy] # you may have other routes here as well
end
Logan Serman
  • 29,447
  • 27
  • 102
  • 141
  • I already have a destroy function for the roster itself in the RostersController, could i name it something else and change the method in the link to match the function? Thanks – Pierre Nov 28 '13 at 17:08
  • Typically you can check if `@player` exists first, if it does then delete only that player's roster (the join table), otherwise delete the roster itself. If that doesn't make sense for your app, you can make a new method, sure. Like `remove` or something, indicating you are removing a player from the roster. Refer to `link_to` documentation, it's all very straightforward. – Logan Serman Nov 28 '13 at 17:10