rails使用关系has_many到

时间:2015-05-19 12:42:25

标签: ruby-on-rails validation

我想验证可加入锦标赛的队员数量。 (max_nb_team是锦标赛中设置限制的字段)
db关系是这样的。
团队< - > TeamTournament< - >赛

但目前我的验证计算所有球队已经加入(写入数据库)但不是加入的球队 因此,当我在锦标赛中有5支球队参加5场比赛并且我再添加一支球队时,请确认计数为5并且不会发起回滚。

我在锦标赛中进行了验证,并将此验证与team_tournament相关联。

class Tournament < ActiveRecord::Base
  has_many :team_tournament, dependent: :destroy
  has_many :teams, through: :team_tournament

  validate :validate_max_nb_team

  def suscribe_teams(array_team)
    array_team.each do |t|
      teams << t
    end
  end

  private
  def validate_max_nb_team
    length_remaining_teams = teams.reject(&:marked_for_destruction?).size
    # length_remaining_teams return five when I'm adding the 6th
    errors.add :max_nb_team, "Max number team has been reached" if length_remaining_teams > max_nb_team
  end
end

class TeamTournament < ActiveRecord::Base
  belongs_to :team
  belongs_to :tournament

  validates_associated :tournament
end

class Team < ActiveRecord::Base
  has_many :team_tournament, dependent: :destroy
  has_many :tournaments, through: :team_tournament
end

class TournamentsController < ApplicationController
  def add_teams
    @tournament = Tournament.find(params[:tournament_id])
    authorize! :edit, @tournament
    names = teams_params

    teams = []
    names.reject { |p| p.blank? }.each do |n|
      teams << Team.create(name: n)
    end

    begin
      @tournament.suscribe_teams(teams)
    rescue ActiveRecord::RecordInvalid => invalid
      return redirect_to(:back, alert: "Max number team has been reached")
    end
    redirect_to(:back)
  end

  private
  def teams_params
    params.require(:teams)
  end
end

所以我想计算参加验证的团队。也许这不是好方法,如果是这样,谢谢你说我如何管理这个问题。

0 个答案:

没有答案