We have a pretty simple application for rails, here is my code:
class Post < ActiveRecord::Base belongs_to :category attr_accessible :category_id, :category_attributes accepts_nested_attributes_for :category, :reject_if => :all_blank end class Category < ActiveRecord::Base has_many :posts end #app/views/posts/_form.html.haml = simple_form_for(@post) do |f| = f.association :category = f.simple_fields_for :category do |cat_f| = cat_f.input :name
Therefore, when creating a new message, I have the opportunity to select a category (from the selection menu) or create a new one (if it does not exist).
I want to confirm that category_id is present if the user does not want to create a new category
I assume that there is some rail to solve this problem. I know that I can’t just add validates :category_id, :presence => true , as this will crash the form when the user decides to create a new category (and don’t choose one from the drop-down list).
Second question: Recently I read a useful tutorial on rails, which shows how to switch between displaying a category selection menu and fields of a new category so that only one of the two is displayed at any time. Has anyone got a link to something like this?
source share