2013-09-21 33 views
3

我正在構建一個每日交易應用程序來訓練學習RoR。布爾活動管理域返回空而不是true或false(Rails 3.2/Active Admin)

在我的交易表單中,我有一個名爲「featured」的布爾字段。如果我選中複選框,交易就會顯示(與草稿相反)。

但是,當我在活動管理員上創建我的交易時,如果選中複選框,我確實會得到'true'(該部分沒問題),但如果我沒有檢查它,我得到'空' '虛假'

我不應該得到錯誤嗎?

這裏是我的文件:

架構遷移:

create_table "deals", :force => true do |t| 
    t.string "title" 
    t.string "description" 
    t.boolean "featured" 
    t.integer "admin_user_id" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 
end 

而主動管理的形式(它使用formtastic的形式在默認情況下,我認爲)

ActiveAdmin.register Deal do 

    controller do 
    with_role :admin_user 
    end 

    form do |f|    

    f.inputs "Content" do 
     f.input :description,  :label => "Deal description" 
     f.input :title,    :label => "Deal title" 

    end 

    f.inputs "Status" do 
    f.input :featured,   :label => "Status of publication (draft or featured)" 
    end 

    f.inputs "Publisher" do 
     f.input :admin_user_id, :as => :select, :collection => AdminUser.all, :label => "Campaign Account Manager" 
    end 

    f.actions 
    end 

end 

任何人有一個想法爲什麼在「精選」列中,當創建Deals時沒有選中「精選」字段的複選框時,我可以讀取「空」而不是「假」。

回答

1

我假設'空',你不是指字面意思,但你的意思是該字段沒有價值或是空的。您沒有爲該字段設置默認值或將任何數據輸入到該字段中,因此它是空的,或者在Ruby本地語言中爲零。要設置默認,你可以做這樣的事情:

create_table "deals", :force => true do |t| 
    t.string "title" 
    t.string "description" 
    t.boolean "featured"   :default => false 
    t.integer "admin_user_id" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 

有設置默認值,以及對於較複雜的值等方法。例如,如果你想爲一個日期時間字段的默認設置爲當前時間,你可以使用一個before_create退出:

before_create :set_foo_to_now 
    def set_foo_to_now 
    self.foo = Time.now 
    end 

或者,你可以簡單地確保當您創建新的記錄,您輸入的值你自己。

作爲參考,請參見ActiveRecord migrations上的此文本。

+0

爲了完整起見,我不得不提到在Ruby中被認爲是錯誤的唯一值包括nil和false。其他任何東西,包括0在其他語言中都是錯誤的,都被認爲是正確的。 –

+0

我的回答有幫助嗎?您還有其它問題麼?如果這解決了,你能接受答案嗎?謝謝... –

+0

對不起,它已經幫助它,是的,它幫助我很好。謝謝! – Mathieu

相關問題