Muflix
Muflix

Reputation: 6798

Rails form select with NULL (no choice) support

How can I add a NULL option to my form select? I have a table:

categories
id
category_id
name

If I'm creating a new category, I want to be able to select the NO_CATEGORY option (NULL value and id).

My view code:

<%= f.collection_select :supercategory_id, Category.all, :id , :name %>

Also, it is a good idea? Isn't it better to have some predefined ROOT category in the database? Thank you.

Upvotes: 3

Views: 3685

Answers (1)

Peter P.
Peter P.

Reputation: 3515

Try:

<%= f.collection_select :supercategory_id, Category.all, :id , :name, :include_blank => true %>

Its ok to have null. Just have your model logic know that it should create a new category and assign it rather than mass assign from the select. Might be something that happens in a before_validation method

Upvotes: 8

Related Questions