简体   繁体   中英

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. 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. This is called white listing your parameters.

You can learn more about strong parameters and white listing in the rails guides .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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