0

无论我在此 Select 元素中选择哪个选项,我都会不断收到 rails 的此验证错误: 位置未包含在列表中

数据库迁移

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
      t.string :name
      t.string :email
      t.string :location
      t.text   :notes

      t.timestamps
    end
  end
end

模型

class Order < ActiveRecord::Base
    has_many :line_items, dependent: :destroy
    LOCATIONS = [ '001 (Lubbock)', '002 (Odessa)', '003 (Midland)', '004 (Lubbock)' ]
    validates :name, :email, presence: true
    validates :location, inclusion: LOCATIONS

    def add_line_items_from_cart(cart)
        cart.line_items.each do |item|
            item.cart_id = nil
            line_items << item
        end
    end
end

表格的相关部分

<div class="field">
   <%= f.label :location %><br>
   <%= f.select :location, Order::LOCATIONS,
                prompt: 'Select your location' %>
</div>

选择元素填充正确,但每次提交表单时都会收到验证错误。有任何想法吗?

编辑 1 (相关表单 HTML)

<div class="field">
    <label for="order_location">Location</label><br>
    <select id="order_location" name="order[location]"><option value="">Select your location</option>
<option value="001 (Lubbock)">001 (Lubbock)</option>
<option value="002 (Odessa)">002 (Odessa)</option>
<option value="003 (Midland)">003 (Midland)</option>
<option value="004 (Lubbock)">004 (Lubbock)</option></select>
  </div>

编辑 2 (控制台输出)

Started POST "/orders" for 127.0.0.1 at 2013-08-11 23:58:50 -0500
Processing by OrdersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Q+XfWgAWXQG6tD710B+3QKlwz7klsuMTG3uZKhmWwA8=", "order"=>{"name"=>"Drew Wyatt", "email"=>"test@example.com", "location"=>"002 (Odessa)", "notes"=>""}, "commit"=>"Place Order"}
  [1m[35mCart Load (0.1ms)[0m  SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1  [["id", 46]]
Unpermitted parameters: location
  [1m[36mLineItem Load (0.1ms)[0m  [1mSELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ?[0m  [["cart_id", 46]]
  [1m[35m (0.1ms)[0m  begin transaction
  [1m[36m (0.1ms)[0m  [1mrollback transaction[0m
  Rendered orders/_form.html.erb (3.2ms)
  Rendered orders/new.html.erb within layouts/application (3.9ms)
  [1m[35mProduct Load (0.1ms)[0m  SELECT "products".* FROM "products" WHERE "products"."id" = ? ORDER BY "products"."id" ASC LIMIT 1  [["id", 2]]
  [1m[36mProduct Load (0.1ms)[0m  [1mSELECT "products".* FROM "products" WHERE "products"."id" = ? ORDER BY "products"."id" ASC LIMIT 1[0m  [["id", 3]]
  Rendered line_items/_line_item.html.erb (2.3ms)
  Rendered carts/_cart.html.erb (3.6ms)
Completed 200 OK in 46ms (Views: 15.3ms | ActiveRecord: 0.7ms)
4

1 回答 1

1

您需要使用Strong Parameters将控制器中的 location 属性列入白名单。

从您的日志中:

不允许的参数:位置

于 2013-08-12T05:05:11.900 回答