2014-01-11 2 views
0

Ruby 2.0.0에서 Rails 4.0.1을 사용하고 있습니다. 나는 카테고리의 간단한 기능을 가지고 있습니다. 각 카테고리는 다른 카테고리에 속하거나 루트 카테고리 (상위 없음) 일 수 있습니다. 그러나 선택 항목에서 공백 ('없음') 값을 선택하면 카테고리를 저장할 수 없습니다. 내 실수는 어디 갔지?선택 필드에서 공백 값을 선택하면 저장할 수 없습니다. (Gem Anceestry)

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 

답변

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 
1

루트 범주의 경우 ancestry 특성은 빈 문자열이 아닌 nil이어야하며 따라서 범주를 저장할 수 없습니다.

+0

을 그러나 "레일"을 만드는 방법 방법? 빈 문자열을 자동으로 nil로 변환하는보기 도우미가 있습니까? –