I'm using Rails 4.0.1 with Ruby 2.0.0. I have a simple functionality of categories. Each category could belong to another one or be a root category (no parent). But if choose blank ('None') value from select, category can not be saved. Where is my mistake?
category.rb
class Category < ActiveRecord::Base
has_many :items
has_ancestry
validates :name, presence: true, length: { minimum: 3 }
mount_uploader :icon, IconUploader
end
categories_controller.rb
def create
@category = Category.new(category_params)
if @category.save
redirect_to admin_categories_path, notice: "Category was successfully created!"
else
render action: "new"
end
end
_form.html.slim
= form_for [:admin, @category] do |f|
= f.label :name
= f.text_field :name
= f.label :ancestry
= f.select :ancestry, Category.all.map {|p| [ p.name, p.id ] }, include_blank: 'None'
= f.label :icon
= f.file_field :icon
= f.submit nil
Transaction log
Started POST "/admin/categories" for 127.0.0.1 at 2014-01-11 12:18:35 +0600
Processing by Admin::CategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"aZS2bO2HEy65cf2jQmm5BTy1VS/1Na1LBN4mHR3FYy4=", "category"=>{"name"=>"Example", "ancestry"=>""}, "button"=>""}
(0.1ms) begin transaction
(0.1ms) rollback transaction
I just came across the same problem. Instead of trying to set the ancestry field on your model, use parent_id instead.
So in your form, use this:
= f.label :parent_id
= f.select :parent_id, Category.all.map {|p| [ p.name, p.id ] }, include_blank: 'None'
Then in your controller, edit the category_params function to allow the attribute to be assigned:
def category_params
params.require(:category).permit(:name, :parent_id)
end