RoR 无法从输入中获取数据到数据库

RoR having trouble getting data from input into the database

我试图将新列 "company" 添加到现有模型 "order.rb" 并且一切似乎都运行良好,但我似乎无法从输入字段中获取数据到新列中在数据库中。

我错过了什么?

数据库中的测试数据:

[1] pry(main)> Order.all
  Order Load (0.1ms)  SELECT "orders".* FROM "orders"
=> [#<Order token: nil, charge_transaction: nil, address_one: "777 Knoll Ln.", address_two: "P.O. Box 743", city: "Los Angeles", state: "CA", zip: "90015", country: "US", status: "SC", number: nil, user_id: "1", shipping: #<BigDecimal:69eed90,'0.595E3',9(36)>, tracking_number: nil, phone: "(626) 513-5035", expiration: "2015-04-03", created_at: "2015-02-06 20:07:04", updated_at: "2015-02-06 20:07:04", payment_option_id: nil, campaign_id: 1, full_name: "John Connor", quantity: 1, terms_of_service: true, order_uri: nil, tax: #<BigDecimal:69f3070,'0.0',9(36)>, company: nil>]

我可以看到公司栏在那里(最后),但无论我在表格中输入什么,我总是得到值 nil。

db/migrate/20150206193142_add_company_to_orders.rb

class AddCompanyToOrders < ActiveRecord::Migration
  def change
    add_column :orders, :company, :string
  end
end

app/controllers/orders_controller.rb 定义创建

    @order = Order.new(
      :user => current_user,
      :campaign => @campaign,
      :quantity => params[:order][:quantity],
      :company => params[:order][:company],
      :full_name => params[:order][:full_name],
      :address_one => params[:order][:address_one],
      :address_two => params[:order][:address_two],
      :city => params[:order][:city],
      :state => params[:order][:state],
      :zip => params[:order][:zip],
      :phone => params[:order][:phone],
      :country => params[:order][:country],
      :terms_of_service => params[:order][:terms_of_service]
    )

app/views/orders/_form.html.erb

%= field_set_tag "Shipping Address", :id => "address" do %>

        <%= f.input :company, :label => "Company" %>
        <%= f.input :full_name, :label => "Full Name" %>
        <%= f.input :address_one, :label => "Street Address 1" %>
        <%= f.input :address_two, :label => "Street Address 2" %>
        <%= f.input :city %>
        <%= f.input :zip, :label => "ZIP or Postal Code", :input_html => { :class => "zip" } %>

<% end %>

您在单独的迁移中添加了 :company,但您似乎忘记在模型中为其添加 attr_accessible


如果您的应用是 运行 rails 3 将此添加到您的 Order.rb 文件:

attr_accessible :company


For rails 4 将属性添加到您的 order_controller.rb 私有方法

def order_params
      params.require(:message).permit(:company, :et_al)
end



参考文献:
attr_accessor - http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods/attr_accessible