2013-02-26 49 views
4

我正在使用Ancestry在Rails中構建一個層次結構類別,並允許用戶選擇他們創建的對象的父級。我顯示使用一個下拉現有類別:Rails血統與零父母

<%= f.input :ancestry, collection: Category.sorted_list %> 

只要用戶選擇現有節點,一切都很好。如果用戶在下拉列表中選擇空白,我希望Ancestry創建一個根節點,但是表單會拋出「無效」錯誤。

我的控制器沒有做任何事情mindblowing:

def update 
    @category = Category.find(params[:id]) 

    respond_to do |format| 
    if @category.update_attributes(params[:category])   
     format.html { redirect_to @category, notice: 'Category was successfully updated.' }   
     format.json { head :no_content } 
    else   
     format.html { render action: "edit" } 
     format.json { render json: @category.errors, status: :unprocessable_entity } 
    end  
    end 
end 

我新來Rails的,所以我不知道如何攻擊這個問題。是否有一種我錯過的Ancestry配置,或者這是一種表單驗證程序,可能是過度保護?

回答

6

發生這種情況的原因是ancestry不能爲nil,因爲所有gem的行爲均基於此屬性,所以手動更改它不是個好主意。對於這種情況,gem還有另一個parent_id屬性,您應該在表單中使用它。

有一個在gem's wiki如何使用ancestry

希望它有助於建立形成了良好的解釋

+0

所以,也許我只是不明白如何正確設置類別模型,然後。如果我將一個:parent_id選擇添加到我的表單中,則會從控制器中收到「Can not mass-assign protected attributes:parent_id」錯誤。 我需要同時擁有一個祖先和一個parent_id列嗎? – 2013-02-26 18:49:16

+1

你不需要在數據庫中有'parent_id',只需要'祖先'列。但是你必須把'parent_id'設置爲'attr_accessible'來避免大量分配錯誤 – 2013-02-26 19:31:02

+0

這樣做,謝謝! – 2013-02-27 02:15:36

1

祖先驗證他的場this

# Validate format of ancestry column value 
validates_format_of ancestry_column, :with => Ancestry::ANCESTRY_PATTERN, :allow_nil => true 

但你不能傳遞nil值形式。所以我這樣做:

before_validation do 
    self.ancestry = nil if self.ancestry.blank? 
end