简体   繁体   English

在Rails的DB中插入记录时未保存任何数据

[英]No data saved when inserting a record in DB in Rails

I am a Ruby On Rails complete beginner and I am writing a small application and I am stuck when trying to add a new record to a table. 我是Ruby On Rails的完整入门者,正在编写一个小应用程序,在尝试向表中添加新记录时遇到了麻烦。 My issue is that no data is sent to be saved. 我的问题是没有数据要发送以保存。

The table structure is: 表结构为:

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

The code for "new" and "create" operations is: “新建”和“创建”操作的代码为:

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

And the view is: 并且视图是:

<%= 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>

I know that no data is sent to be saved because I changed 我知道没有数据要保存,因为我更改了

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

to

params.permit(:name, :description)

And a blank record was inserted. 并插入一个空白记录。 Both fields are blank. 两个字段均为空白。

I will very much appreciate your comments to help solve my issue. 非常感谢您的评论,以帮助解决我的问题。

Respectfully, 尊敬,
Jorge Maldonado 豪尔赫·马尔多纳多

You should have 你应该有

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

What this does is tell rails that you will be accepting a committee object in the params hash, and that you explicitly will only be accepting the name and description fields for that committee. 这样做是告诉Rails您将接受params哈希中的committee对象,并且您明确将仅接受该委员会的namedescription字段。 This is called white listing your parameters. 这称为列出您的参数的白名单。

You can learn more about strong parameters and white listing in the rails guides . 您可以在rails指南中了解有关强参数和白名单的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM