我正在使用Rails 4.0.1和Ruby 2.0.0。 我有一个简单的类别功能。每个类别可以属于另一个类别或是根类别(没有父类别)。但是如果从select中选择空白('None')值,则无法保存类别。我的错误在哪里?
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
交易日志
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
答案 0 :(得分:1)
对于根类别,ancestry
属性必须为nil
,而不是空字符串,因此您无法保存该类别。
答案 1 :(得分:1)
我刚遇到同样的问题。而不是尝试在模型上设置祖先字段,而是使用parent_id。
所以在你的表格中,请使用:
= f.label :parent_id
= f.select :parent_id, Category.all.map {|p| [ p.name, p.id ] }, include_blank: 'None'
然后在您的控制器中,编辑category_params函数以允许分配属性:
def category_params
params.require(:category).permit(:name, :parent_id)
end