2017-03-05 77 views
1

我是一個Ruby On Rails完整的初學者,我正在編寫一個小應用程序,並且在試圖將新記錄添加到表時遇到困難。我的問題是沒有數據被髮送保存。在數據庫中插入記錄時沒有數據保存在Rails中

表結構是:

create_table "committees", force: :cascade do |t| 
t.string "name",  limit: 50 
t.text  "description" 
t.datetime "created_at",    null: false 
t.datetime "updated_at",    null: false 
end 

的代碼 「新」 和 「創造」 的操作是:

def new 
    @committee = Committee.new 
end 

def create 
    @committee = Committee.new(committee_params) 

    if @committee.save 
    redirect_to(committees_path) 
    else 
    render("new") 
    end 
end 

private 

def committee_params 
    params.require(:name).permit(:description) 
end 

和視圖是:

<%= link_to("<< Back to List", committees_path, :class => "back-link") %> 

<div> 
    <h2>Create Committee</h2> 
    <%= form_for(@committee) do |f| %> 
     <table> 
      <tr> 
       <td>Name</td> 
       <td><%= f.text_field(:name) %></td> 
      </tr> 
      <tr> 
       <td>Description</td> 
       <td><%= f.text_field(:description) %></td> 
      </tr> 
     </table> 

     <div> 
      <%= f.submit("Create Committee") %> 
     </div> 
    <% end %> 
</div> 

我知道沒有數據發送被保存,因爲我改變了

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

params.permit(:name, :description) 

,並插入一個空白記錄。兩個字段都是空白的。

我會非常感謝您的意見,以幫助解決我的問題。

尊敬,
豪爾赫·馬爾多納多

回答

4

你應該有

def committee_params 
    params.require(:committee).permit(:name, :description) 
end 

這樣做是告訴你將接受在params哈希表一個committee對象的軌道,而您明確將只接受該委員會的namedescription字段。這被稱爲白名單你的參數。

您可以在the rails guides中瞭解有關強參數和白名單的更多信息。

+0

感謝您的超快速和準確的響應和解釋。它正在工作。 – user3059248

+0

太棒了!如果答案解決了您的問題,您是否介意接受答案?很高興我能幫上忙! – Mark