开发者

Handling accepts_nested_attributes_for children errors

My setup: Rails 2.3.10, Ruby 1.8.7

users_controller.rb

 def character
  @user = User.find(params[:id])

  respond_to do |format|
  if @user.update_attributes(params[:user])
   format.json { render :json => @user }
  else
   format.json { render :json=> @user.errors.full_messages, :status => :unprocessable_entity }
  end
 end
end

user.rb

 accepts_nested_attributes_for :characters
 has_many :characters
end

character.rb

 belongs_to :user
 before_create :check_count

 def check_count
  if Characters.find(:all, :conditions => ["user_id = ?", self.user_id).count ==开发者_如何学Python 3
   errors.add_to_base I18n.t :exceeds 
   false
  end
 end
end

In the users character method (it's a custom method), I want to create a child character only if there aren't already 3 characters for the user. My question is how to return the error message to the @user object from within check_count method, currently errors refer to the character object, not @user. Thanks in advance for your help.


After some digging around, I found the solution

user.rb

accepts_nested_attributes_for :characters, :before_add :set_parent
has_many :characters

def set_parent(character)
 character.user ||= self
end

end

character.rb

 belongs_to :user
 before_create :check_count

 def check_count
  if Characters.find(:all, :conditions => ["user_id = ?", self.user_id).count == 3
   self.user.errors.add_to_base I18n.t :exceeds 
   false
  end
 end
end

Hope this helps someone else.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜