我正在尝试修改RESTful控制器中的逻辑。在当前的实现中,我有以下内容:
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
has_many :members, :dependent => :destroy
def add_player(player_id)
current_member = members.find_by_player_id(player_id)
if current_member
# will not add duplicate member
else
current_member = members.build(:player_id => player_id)
end
current_member
end
这缺少一些功能,因为我希望能够通过检查成员对玩家的其他属性来控制是否保存成员。在当前的实现中,如果我尝试添加已经存在的成员,即使没有添加成员,它仍然会被重定向到@team并注意到“成功添加成员”。如果我尝试通过以下操作删除冗余,则控制器会添加重复的成员。
@team = current_team
@member = @team.add_player(:player_id)
为什么我当前的逻辑允许我不保存重复的成员,但仍然响应@ member.save路由?我该如何正确控制它?
答案 0 :(得分:1)
而不是
def add_player(player_id)
current_member = members.find_by_player_id(player_id)
if current_member
# will not add duplicate member
else
current_member = members.build(:player_id => player_id)
end
current_member
end
尝试:
Member.rb
validates_uniqueness_of :player_id, :scope => :team_id
team.rb
def add_player(player_id)
current_member = members.build(:player_id => player_id)
current_member
end
答案 1 :(得分:0)
ntenisOT是正确的。当您在team.rb中调用build时,您实际上并没有保存成员资格,而只是将该玩家添加到该特定团队对象的团队中。此外,控制器仍然响应保存,因为您正在调用返回true的播放器上保存。