2015-01-21 24 views
0

我在創建論壇時遇到了令人討厭的問題,我的form_for方法。每次我嘗試提交創建論壇時,我都會從Rails收到此錯誤。 param is missing or the value is empty: forumRails form_for援助:param丟失或值爲空

的問題是在我的forums_param方法:

def forum_params 
    params.require(:forum).permit(:id, :name, :position) 
end 

論壇部分不存在。下面的代碼是我的看法形式:

well.span11 
    .span7 
    = form_for @forum, url: forums_path, html: { method: :post } do |f| 
     = render partial: "form", locals: { f: f } 
     .actions 
     = submit_tag 'Create', { class: 'btn btn-primary btn-small' } 
.clear 

和部分它呈現:

%fieldset 
    %div{class: 'control-group'} 
    = label_tag :title, "Title (required)", class: 'control-label required' 
    %div{class: 'controls'} 
     = text_field_tag :name, nil, class: 'span8' 
    - if @forum.errors[:name] 
     %p{class: 'error'}#{@forum.errors[:name]} 

    %div{class: 'control-group'} 
    = label_tag :position, "Position", class: 'control-label' 
    %div{class: 'controls'} 
     = text_field_tag :position, nil, size: 5 

    %div{class: 'control-group'} 
    = label_tag :description, "Description", class: 'control-label' 
    %div{class: 'controls'} 
     = text_area_tag :description, nil, rows: 10, class: 'span10' 

下面是控制器代碼:

def new 
    @forum = Forum.new 
    end 

    def create 
    @forum = Forum.new(forum_params) 
    if @forum.save 
     redirect_to forums_path, flash: { success: t('.success') } 
    else 
     redirect_to forums_path, flash: { error: t('.error') } 
    end 
    end 

我不知道是什麼正在這裏。我已經實施了這些職位下描述的建議。

Solution 1

Solution 2

Solution 3

這裏有什麼問題?幫助將不勝感激。

+0

你得到這個錯誤的頁面的網址/路徑是什麼? – miler350 2015-01-21 03:36:42

回答

0

從我所看到的,你錯過了一堆東西,因爲它從視圖到控制器。你有描述字段,標題等。這些不是被分解成forum_params

如果用戶可以添加並更改它們,它們必須包含在強參數中。我不認爲身份證應該在那裏,但...用戶不應該被允許改變身份證。創建記錄時應由AR創建。

0

這裏的問題似乎是您使用<foo>_tag而不是f.<foo>_field

當您使用<foo>_tag時,帶有您給它的屬性的文字標籤出現在DOM中。

text_field_tag例如:

text_field_tag 'title' 
# => <input id="title" name="title" type="text" /> 

基於來自文檔的例子。來源:the Ruby on Rails API docs for text_field_tag

而當您使用f.<foo>_field時,name屬性在模型名稱下是命名空間。

f.text_field例如:

text_field(:post, :title, size: 20) 
# => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" /> 

來源:the Ruby on Rails API docs for text_field

稍微更深入的說明

隨着上面的示例中,第一被提交時,該PARAMS看起來像:

{ ..., "title" => "user's input", ... } 

由此可以看出,如果您的控制器試圖使:post超出此參數散列,則它是nil,並且它會拋出您遇到的錯誤。

用於在第一部分中的第二示例中的PARAMS看起來像:

{ ..., "post" => {"title" => "user's input", ... }, ... } 

當控制器試圖得到:post出這個散列的,它得到含有title子哈希(和任何其它形式的字段)。

我希望這可以解決您的問題!

相關問題