以多对多关系删除/删除数据

时间:2015-06-29 22:01:54

标签: ruby-on-rails ruby-on-rails-4

#The various models
class Team < ActiveRecord::Base
  has_many :competition_teams
  has_many :competitions, through: :competition_teams
end

class Competition < ActiveRecord::Base
  has_many :competition_teams
  has_many :teams, through: :competition_teams
end

class CompetitionTeam < ActiveRecord::Base
  belongs_to :team
  belongs_to :competition
end

#The form I'm using to add teams to the competition

= semantic_form_for @competition do |f|
  = f.inputs :name do
     = f.input :teams, as: :select, collection: current_user.teams.select{|t| !@competition.teams.include?(t)}
  = f.actions do
    = f.action :submit, as: :button

#Competition update action, used to add teams

def update
  @competition = Competition.find(params[:id])
  teams = competition_params[:team_ids] + @competition.teams.pluck(:id)
  team = Team.find(competition_params[:team_ids][1])

  if team.users.pluck(:id).include?(current_user.id) && @competition.update_attribute(:team_ids, teams)
    redirect_to @competition
  end
end

所以我想做的是创建一个按钮(或链接),允许用户从竞争对手中删除他们的团队。这应该通过自定义操作还是某种形式完成? 我真的不知道从哪里开始,所以任何帮助都非常感激

1 个答案:

答案 0 :(得分:0)

默认情况下,form_for会发出帖子请求,如果对象是新对象,则转到create操作,如果对象已在,则转到update操作数据库。您想要做的是向delete行动请求您将从竞赛中删除该团队。你应该首先得到@competition_team对象。

@competition_team = CompetitionTeam.new

然后

= semantic_form_for @competition_team, method: 'delete' do |f|

然后在您的competition_team控制器中,创建您的销毁操作以及您的代码,以便从竞争对手中删除该团队。

def destroy
   #your code
end

此外,请务必在路线中定义销毁操作。