简体   繁体   中英

adding new element in rails form

What are the the correct steps in adding new text fields to a rails form such that rails will register it?

current form:

<%= form_for(@order) do |f| %>
  <% if @order.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@order.errors.count, "error") %> prohibited this order from being saved:</h2>

      <ul>
      <% @order.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  # I WANT TO ADD A QUANTITY FIELD TO MY FORM
  <div><%= f.label :quantity %><br />
    <%= f.text_field :quantity, autofocus: true %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

after adding the above code, I modified my database migration.

[timestamp]_create_orders.rb

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
        # added this line to the database since I want to have a new field in my form
        t.string :quantity

        t.timestamps
    end
  end
end

After that I tried to go to orders/new to create a new order to see if my form is outputting correctly, but instead I get an undefined method "quantity" error at /orders/new

What am I doing wrong here and what should I do to fix it?

If you wanted to add extra fields to a table (as in adding/editing attributes to/of an existing model) that you have already created, use the migration generator to (2.1) create a standalone migration. Don't edit a migration file after you have run

rake db:migrate

Preffered solution:

You can just undo whatever changes you made in that migration file and just use a migration generator. Then migrate. Here is the sample code (untested)

rails generate migration add_quantity_to_orders quantity:string
rake db:migrate

Non-preferred solution

As a simple fix since I don't know how many migrations you have, I think you should drop everything and recreate the table. You don't have to undo the changes you have made.

rake db:migrate VERSION=0
rake db:migrate

That way it recreates the tables for you. This is the price you will pay for fiddling with already migrated files.

I hope this solves your problem.

Its clearly shown that migration is edited.

In Rails App, never edit a migration. create a new migration for adding a column.

After this. Make sure you have attr_accessor if you are not on RAils 4.else add permit on each column in controller.

params.require(:orders).permit(:quantity)

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