2013-07-19 91 views
5

對不起,如果標題有點混亂。我有一個Item的表單,其中name。有一個文本字段,用戶可以在其中輸入名稱並提交。但是,如果用戶沒有輸入任何內容並點擊提交,Rails會給我一個param not found: item錯誤,我不確定誰來解決這個問題。Rails 4:如何處理沒有選擇任何內容的提交表單?

items_controller.rb

def new 
    @item = Item.new() 

    respond_to do |format| 
    format.html 
    format.json { render json: @item } 
    end 
end 

def create 
    @item = Item.new(item_params) 

    respond_to do |format| 
    if @item.save 
     format.html { redirect_to items_path } 
     format.json { render json: @item, status: :created, location: @item } 
    else 
     format.html { render action: 'new', :notice => "Input a name." } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
    end 
    end 
end 

private 

def item_params 
    params.require(:item).permit(:name) 
end 

應用程序/視圖/項目/ new.html.haml

= form_for @item do |f| 
    = f.label :name 
    = f.text_field :name 
    = f.submit "Submit" 

的params.require(:項目)的部分是什麼原因造成的錯誤。當params [:item]不存在時處理錯誤的約定是什麼?

+0

你不應該得到這個錯誤,什麼是張貼PARAMS當你看到日誌? –

回答

7

答案已經晚了,但我仍然會寫給別人。如rails guides所述,您需要在強參數中使用fetch而不是require,通過使用fetch,您可以在沒有任何內容作爲輸入傳遞時提供默認值。喜歡的東西:

params.fetch(:resource, {}) 
1

更新:

架式rails4應用: https://github.com/szines/item_17751377

如果用戶保留名稱字段爲空時創建新的項目它的工作原理...

看來,它的工作原理沒有問題。 ..

Development.log顯示如果用戶保持一個字段爲空,參數將如下所示:

"item"=>{"name"=>""} 

總有一些事情在散...

正如邁克李的評論,一些錯誤已經提到......因爲不能爲空此PARAMS [:項目] ...

如果是nil,您可以檢查是否有零,如.nil?,在這種情況下,params[:item].nil?將是true。或者你可以使用.present?正如sytycs已經寫過的一樣。

以前的答案:

如果有情況時:項目是空的,你應該只使用PARAMS [:項目]沒有要求。約

def item_params 
    params[:item].permit(:name) 
end 

更多信息需要strong_parameters.rb源代碼:

# Ensures that a parameter is present. If it's present, returns 
# the parameter at the given +key+, otherwise raises an 
# <tt>ActionController::ParameterMissing</tt> error. 
# 
# ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person) 
# # => {"name"=>"Francesco"} 
# 
# ActionController::Parameters.new(person: nil).require(:person) 
# # => ActionController::ParameterMissing: param not found: person 
# 
# ActionController::Parameters.new(person: {}).require(:person) 
# # => ActionController::ParameterMissing: param not found: person 
def require(key) 
    self[key].presence || raise(ParameterMissing.new(key)) 
end 
+0

這給了我一個'nil:NilClass'錯誤'未定義的方法'許可'。如果params [:item]不只是空的,但它本身也是零,我該怎麼辦? – justindao

+0

我搭建了一個Rails應用程序,找出可能是你的問題。你可以在這裏找到:https://github.com/szines/item_17751377 – Zoltan

0

我個人沒有切換到強的參數,所以我不知道應該如何處理這樣的:

params.require(:item).permit(:name) 

但你總是可以用類似的東西檢查物品的存在:

if params[:item].present? 
    … 
end 
相關問題