开发者

Rails 3: Custom Model Notices

Currently I verify that there are no duplicated Members when trying to create a new Member and add it to a Team.

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 => :unproce开发者_运维百科ssable_entity }
     end
   end
 end

team.rb

def add_player(player_id)
    current_member = members.build(:player_id => player_id)
    current_member
end

I want to add some logic to my add_player method in team.rb that checks various properties of the player that is being added. This action will require multiple failure messages, other than 'Member already exists.' How do I do this in the Model layer?


You can create custom errors on ActiveRecord models. These custom errors can have their own messages, which you can query in your controller if the save is not successful:

# 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

More information on custom ActiveRecord validation errors here: http://api.rubyonrails.org/v2.3.8/classes/ActiveRecord/Errors.html#M001725


The controller logic to display all errors from base worked. However, I was not able to add errors from the add_player method as Ben suggested. I instead created separate custom validations as such:

Team.rb

validate validation_name

def validation_name
  if condition
    errors.add_to_base "Error Message"
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜