简单表单未传递ID

时间:2015-09-14 12:05:54

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

您好我有一个分类视图。您可以创建一个类别,如“衬衫”,然后从已经制作的尺寸中选择,如XS,S,M,大。当你创建一个新的类别时,nill会出现。

应该选择所有类别。

见下面size_id:nil

2.2.1 :006 > Category.last
  Category Load (0.4ms)  SELECT  "categories".* FROM "categories"  ORDER BY "categories"."id" DESC LIMIT 1
 => #<Category id: 30, name: "test", ancestry: "20", created_at: "2015-09-14 11:09:07", updated_at: "2015-09-14 11:09:07", size_id: nil>

当我使用以下代码时,它会传递id <%= f.collection_select :size_id, Dize.order(:title), :id, :title, {prompt: "Select Parrent ID If Applicable"},include_blank: true %>,所以我知道问题与我的表单有关。

我的观点。我使用简单的形式宝石。所以我目前正在使用<%= f.association :sizes %>

<div class="container">
  <div class=“row”>
    <div class="col-md-6 col-md-offset-3">
      <div class="panel panel-primary">
        <div class="panel-body">
                    <%= simple_form_for(@category) do |f| %>
                      <div class="form-inputs">
                        <%= f.input :name %>
              <%= f.association :sizes %>
              <%= f.collection_select :parent_id, Category.order(:name), :id, :name, {prompt: "Select Parrent ID If Applicable"},include_blank: true %>
            </div>
            <div class="form-actions"><%= f.button :submit %></div>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>

类别控制器。

class CategoriesController < ApplicationController
  before_action :set_category,   only: [:show]
  before_action :admin_user,     only: [:destroy, :index, :edit, :show]

  def index
    @categories = Category.all
  end

  def show
    @tags = Item.where(category_id: @category.id).tag_counts_on(:tags)
    if params[:tag]
      @items = Item.tagged_with(params[:tag])
    else
      @items = Item.where(category_id: @category.id).order("created_at DESC")
    end
  end

  def new
    @category = Category.new
  end

  def edit
    @category = Category.find(params[:id])
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to @category
      flash[:success] = "You have created a new category"
    else
      flash[:danger] = "Your category didn't save"
      render "new"
    end
  end

  def update
    @Cateogry = Category.find(params[:id])
    if @Cateogry.update(category_params)
       redirect_to @Cateogry
       flash[:success] = 'Category was successfully updated.'
    else
      render "edit"
    end
  end

  def destroy
    Category.find(params[:id]).destroy
    flash[:success] = "Category deleted"
    redirect_to categories_path
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:name, :parent_id, :size_id)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.try(:admin?)
    end

end

我的计划

ActiveRecord::Schema.define(version: 20150914095836) do

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.string   "ancestry"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "size_id"
  end

  add_index "categories", ["ancestry"], name: "index_categories_on_ancestry"

  create_table "items", force: :cascade do |t|
    t.string   "title"
    t.decimal  "price"
    t.text     "description"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.integer  "user_id"
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
    t.integer  "category_id"
  end

  add_index "items", ["user_id", "created_at"], name: "index_items_on_user_id_and_created_at"
  add_index "items", ["user_id"], name: "index_items_on_user_id"

  create_table "sizes", force: :cascade do |t|
    t.text     "title"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
  end

  create_table "taggings", force: :cascade do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"

  create_table "tags", force: :cascade do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true

  create_table "users", force: :cascade do |t|
    t.string   "username"
    t.string   "email"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "password_digest"
    t.string   "remember_digest"
    t.boolean  "admin",               default: false
    t.string   "activation_digest"
    t.boolean  "activated",           default: false
    t.datetime "activated_at"
    t.string   "reset_digest"
    t.string   ">"
    t.datetime "reset_sent_at"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.text     "description"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true

end

服务器日志

Started POST "/categories" for ::1 at 2015-09-14 22:22:52 +1000
Processing by CategoriesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"HTiUBJc6PNI+CTOKZ8c6Zb1oOYpdfnlwju9IxTAcDJxcNVerkeE/3YEISy04QW1eOxpVWSUfO4D/CPV5srxdIg==", "category"=>{"name"=>"test032", "size_ids"=>["", "1"], "parent_id"=>"20"}, "commit"=>"Create Category"}
Unpermitted parameter: size_ids
  Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 20]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "categories" ("name", "ancestry", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "test032"], ["ancestry", "20"], ["created_at", "2015-09-14 12:22:52.177014"], ["updated_at", "2015-09-14 12:22:52.177014"]]
   (0.9ms)  commit transaction
Redirected to http://localhost:3000/categories/36
Completed 302 Found in 5ms (ActiveRecord: 1.4ms)


Started GET "/categories/36" for ::1 at 2015-09-14 22:22:52 +1000
Processing by CategoriesController#show as HTML
  Parameters: {"id"=>"36"}
  Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 36]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 53]]
   (0.4ms)  SELECT COUNT(*) FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN items ON items.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Item' AND taggings.context = 'tags') AND (taggings.taggable_id IN(SELECT items.id FROM "items" WHERE "items"."category_id" = 36)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
  Item Load (0.1ms)  SELECT "items".* FROM "items" WHERE "items"."category_id" = ?  ORDER BY created_at DESC  [["category_id", 36]]
  Rendered categories/show.html.erb within layouts/application (1.7ms)
  Rendered layouts/_header.html.erb (0.7ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 262ms (Views: 258.8ms | ActiveRecord: 0.7ms)

ROR的Paras

Started POST "/categories" for ::1 at 2015-09-14 22:44:10 +1000
Processing by CategoriesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"CUvynavkQgbHolVu67aEyQh1UM5uFhsAts50/wylFyNIRjEyrT9BCXijLcm0MNPyjgc8HRZ3WfDHKclDjgVGnQ==", "category"=>{"name"=>"Test12", "size_ids"=>["", "1"], "parent_id"=>"20"}, "commit"=>"Create Category"}
Unpermitted parameter: size_ids
  Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 20]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "categories" ("name", "ancestry", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "Test12"], ["ancestry", "20"], ["created_at", "2015-09-14 12:44:10.007917"], ["updated_at", "2015-09-14 12:44:10.007917"]]
   (0.7ms)  commit transaction
Redirected to http://localhost:3000/categories/39
Completed 302 Found in 5ms (ActiveRecord: 1.2ms)


Started GET "/categories/39" for ::1 at 2015-09-14 22:44:10 +1000
Processing by CategoriesController#show as HTML
  Parameters: {"id"=>"39"}
  Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 39]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 53]]
   (0.4ms)  SELECT COUNT(*) FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN items ON items.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Item' AND taggings.context = 'tags') AND (taggings.taggable_id IN(SELECT items.id FROM "items" WHERE "items"."category_id" = 39)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
  Item Load (0.1ms)  SELECT "items".* FROM "items" WHERE "items"."category_id" = ?  ORDER BY created_at DESC  [["category_id", 39]]
  Rendered categories/show.html.erb within layouts/application (1.7ms)
  Rendered layouts/_header.html.erb (0.6ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 247ms (Views: 243.4ms | ActiveRecord: 0.8ms)

分类模型。

class Category < ActiveRecord::Base
    has_ancestry
    has_many :items
    has_many :sizes
    validates :name, presence: true, length: { maximum: 20 }
end

尺寸模型

class Size < ActiveRecord::Base
    validates :title, presence: true, length: { maximum: 15 }
    validates :title, uniqueness: true
    belongs_to :category
end

1 个答案:

答案 0 :(得分:0)

<%= f.association :size, collection: Size.all, label_method: title, as: :select %>

更改大小的选择标记并检查。