Topic: Nested models and forms

Hello guys,

I'm currently building an app in which a user can create posts. A post belongs to a category ALWAYS. In the create form the user can write the title of the post, content and the category name.

When the user submits the form and the category doesn't exists, the new category should be saved into the categories table and the new post should reference this category. If the category already exists the new post record should simply reference it.

I did the following at first:

class Post < ActiveRecord::Base 

  attr_accessor :category_name
  belongs_to :category  
  before_save :update_category

  private

  # Callback to handle category
  def update_category
    category = Category.find(:first, :conditions => ['name = ?', category_name])
    if category
      self.category = category
    else
      self.category = Category.create(:name => category_name)
    end
  end

end

I use the attr_accessor 'category_name' as the name for the textfield in the form. The problem I'm facing is that I want to be able to perform validation on that category name and render those errors in the form. For example, the category name should not be blank (I want to show this error in the form if that's the case) and should have a certain format, etc...

What's the best way to check if category name is valid and render those errors on my form?

Thank you,

Elías

P.D. I'm using auto-complete for the categories name on my form (Just in case someone wonders)

Last edited by elioncho (2010-06-11 23:23:23)

Re: Nested models and forms

Won't you have these validations in the Category model? If you use create! rather than create will it help?

Re: Nested models and forms

specious wrote:

Won't you have these validations in the Category model? If you use create! rather than create will it help?

Of course. I'll have those validations in the category model but I'm creating the category through the Post model.