0

我正在使用带有 Ruby 2.0.0 的 Rails 4.0.1。我有一个简单的类别功能。每个类别可以属于另一个类别,也可以是根类别(无父类别)。但是如果从选择中选择空白('None')值,则无法保存类别。我的错误在哪里?

类别.rb

class Category < ActiveRecord::Base

  has_many :items
  has_ancestry

  validates :name, presence: true, length: { minimum: 3 }
  mount_uploader :icon, IconUploader

end

类别控制器.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
4

2 回答 2

1

对于根类别,ancestry属性必须是nil,而不是空字符串,因此不能保存类别。

于 2014-01-11T06:43:04.463 回答
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
于 2014-02-09T04:20:54.240 回答