如何使用checkobxes更新rails中的中间表?

时间:2012-01-31 06:13:41

标签: ruby-on-rails-3

我不知道如何计算出这个,因为我不知道如何更新我的中间表,而不必执行delete_all。或者在哪里进行插入和删除等。 我有三个班级:

class User < ActiveRecord::Base
  has_many :players
  has_many :teams, :through => :players 
end

class Team < ActiveRecord::Base
  has_many :players
end

class Player < ActiveRecord::Base
  belongs_to :team
  belongs_to :user
   (contains other columns like, is_captain, has_paid, etc.)
end

我正在显示一个带复选框的页面,您可以选择您希望加入团队的“用户”(来自您的地址簿)。因此,想象一下列出了25个名字,其中一些已经被检查过,而另一些则没有。如何保存复选框的数据,因为它们可能有3种不同的状态:1)插入全新的播放器(在播放器中插入行)2)从团队中删除播放器(删除现有播放器)或3)什么都不做(你不玩的播放器)想要你的团队)

我遇到的问题是当你“取消选中”一个盒子时,那么前端不会将它发送到后端?有什么想法可以做得很好吗?

1 个答案:

答案 0 :(得分:0)

不确定这是否是执行此操作的最佳方式,但它有效,我愿意接受改进此代码的建议

    params[:team][:user_ids] ||= []
    @team = Team.find(params[:team][:id])
    current_players = @team.players
    current_players_user_ids = current_players.collect { |player| player.user_id }
    user_ids = params[:team][:user_ids]
    puts "input ids #{user_ids}"
    #add current_user because checkbox does not pass them in since its 'disabled'
    user_ids << current_user.id

    #delete the current_players that are not in the the received 'checkboxes'
    current_players_user_ids.each do |current_player_user_id|
      unless user_ids.include?(current_player_user_id)
        Player.delete_all(:team_id => @team.id, :user_id => current_player_user_id)
      end
    end

    #iterate through input ids and run 'inserts' on those who are not current-players
    user_ids.each do |user_id|
      unless current_players_user_ids.include?(user_id)
        player = Player.new(:user_id=>user_id, :team_id=>@team.id)
        @team.players << player
      end
    end