删除HABTM对象

时间:2013-11-27 19:11:15

标签: ruby-on-rails ruby-on-rails-4 has-and-belongs-to-many

我有以下代码,它给了我一个ActionView::Template::Error (undefined method roster_path'对于#<#:0x007fe34005c208>):`

虽然在后台它会删除关联player_roster(拥有并且属于很多),但是当我按下链接时我想删除它。

名单路径嵌套在一个团队中,但问题在于名册和球员。

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

:更新

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

1 个答案:

答案 0 :(得分:0)

您现在的行为方式会在页面加载时调用delete。您无法链接到任意Ruby代码,您需要链接到将执行您的逻辑的路由和控制器操作。

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

此链接将使用DELETE HTTP操作路由到players /:id / rosters /:id,Rails将路由到destroy方法。

class RostersController < ApplicationController

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

end

您还需要在config / routes.rb

中设置player_roster_path作为路由
resources :players do
  resources :rosters, only: [:destroy] # you may have other routes here as well
end