目前,我在尝试创建新成员并将其添加到团队时验证没有重复的成员。
members_controller.rb
def create
@team = current_team
player = Player.find(params[:player_id])
@member = @team.add_player(player.id)
respond_to do |format|
if @member.save
format.html { redirect_to(@team, :notice => 'Member was successfully added.') }
format.js { @current_member = @member }
format.xml { render :xml => @member,
:status => :created, :location => @member }
else
format.html { redirect_to(@team, :notice => 'Member already exists.') }
format.xml { render :xml => @member.errors,
:status => :unprocessable_entity }
end
end
end
team.rb
def add_player(player_id)
current_member = members.build(:player_id => player_id)
current_member
end
我想在team.rb中的add_player方法中添加一些逻辑,用于检查正在添加的播放器的各种属性。除“会员已存在”外,此操作将需要多条失败消息。我如何在模型层中执行此操作?
答案 0 :(得分:1)
您可以在ActiveRecord模型上创建自定义错误。这些自定义错误可以有自己的消息,如果保存不成功,您可以在控制器中查询:
# app/models/team.rb
def add_player(player_id)
current_member = members.build(:player_id => player_id)
errors.add(:player_id, 'Custom error message here') if condition
errors.add(:base, 'Custom error message here') if condition
current_member
end
# app/controllers/members_controller.rb
def create
@team = current_team
player = Player.find(params[:player_id])
@member = @team.add_player(player.id)
respond_to do |format|
if @member.save
format.html { redirect_to(@team, :notice => 'Member was successfully added.') }
format.js { @current_member = @member }
format.xml { render :xml => @member,
:status => :created, :location => @member }
else
format.html { redirect_to(@team, :notice => @member.errors.full_messages) }
format.xml { render :xml => @member.errors,
:status => :unprocessable_entity }
end
end
end
有关自定义ActiveRecord验证错误的详细信息,请访问:http://api.rubyonrails.org/v2.3.8/classes/ActiveRecord/Errors.html#M001725
答案 1 :(得分:0)
控制器逻辑显示基础工作的所有错误。但是,我无法像Ben建议的那样在add_player方法中添加错误。我改为创建单独的自定义验证:
Team.rb
validate validation_name
def validation_name
if condition
errors.add_to_base "Error Message"
end
end