1

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 == 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.

1
  • In future, please separate the individual files in your post as shown in the updated version of this post. It helps make them extra-readable. Commented Apr 9, 2011 at 0:48

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.