2015-06-29 168 views
0
#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| [email protected]?(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 

所以我想要做的是创建一个按钮(或链接),允许用户从竞争对手中删除他们的团队。这应该通过自定义操作还是某种形式来完成? 我真的不知道在哪里可以从这里走,所以任何帮助是非常赞赏以多对多的关系删除/删除数据

回答

0

默认情况下,form_for将使POST请求,并转到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 

此外,请确保在您的路线中定义销毁行为。

+0

所以我应该为competition_teams创建一个控制器,它只能用于一个目的,删除CompetitionTeams。我想避免这种情况,但它使一切变得更加容易。我可以在比赛控制器中使用摧毁动作来做同样的事情,但我想最好是这样做。非常感谢你! 获得@team对象也很难,因为我没有team_id来获取它。我查看并希望编辑的页面是'比赛/:id'。 – norflow

+0

在比赛控制器中创建它是没有意义的,因为那是您创建销毁行为来摧毁竞争对手的地方。这将会让人困惑。 – forthowin

相关问题