在数据库中插入记录时没有数据保存在Rails中

问题描述:

我是一个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) 

,并插入一个空白记录。两个字段都是空白的。

我会非常感谢您的意见,以帮助解决我的问题。

尊敬,
豪尔赫·马尔多纳多

你应该有

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

这样做是告诉你将接受在params哈希表一个committee对象的轨道,而您明确将只接受该委员会的namedescription字段。这被称为白名单你的参数。

您可以在the rails guides中了解有关强参数和白名单的更多信息。

+0

感谢您的超快速和准确的响应和解释。它正在工作。 – user3059248

+0

太棒了!如果答案解决了您的问题,您是否介意接受答案?很高兴我能帮上忙! – Mark