1

我有我希望能夠與不同模型一起使用的分類模型。這就是我最終使用has_many使用Polymorphic的方式。建立Rails窗體以保存多態協會

隨着Rails_admin一切正常,沒有問題。但是,當我想自己創建一個表單時,我似乎無法保存它。以下是我有:

category.rb

class Category < ActiveRecord::Base 
    has_many :categorizings, inverse_of: :category, dependent: :destroy 
    has_many :cars, through: :categorizings, :source => :categorizable, 
     :source_type => 'Car' 
end 

categorizing.rb

class Categorizing < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :categorizable, :polymorphic => true 
end 

car.rb

class Car < ActiveRecord::Base 
    has_many :categorizings, :as => :categorizable, inverse_of: :car, dependent: :destroy 
    has_many :categories, through: :categorizings 
end 

vendor.rb

class Vendor < ActiveRecord::Base 
    has_many :categorizings, :as => :categorizable, inverse_of: :vendor, dependent: :destroy 
    has_many :categories, through: :categorizings 
end 

cars_controller.rb

class CarsController < ApplicationController 
    def new 
    @car = Car.new 
    end 
    def create 
    @car = current_user.cars.build(car_params) 
     if @car.save 
     redirect_to @car 
     else 
      render 'new' 
     end 
    end 
    private 
    def car_params 
    params.require(:car).permit(:name, :details, :type, :category_ids => []) 
    end 
end 

schema.rb

create_table "categories", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "categorizings", force: :cascade do |t| 
    t.integer "category_id" 
    t.integer "categorizable_id" 
    t.string "categorizable_type" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

add_index "categorizings", ["categorizable_type", "categorizable_id"], name: "index_categorizings_on_categorizable_type_and_categorizable_id", using: :btree 

這是我在形式

<%= f.collection_select :category_ids, Category.all, :id, :name %> 

我收到此錯誤: 不允許的參數:category_ids

我很困惑鑽機現在,並在模型中丟失。不知道這是最好的方法或不。如果有人能告訴我我犯了什麼錯誤,我會很高興。

+0

你也可以包括DB/schema.rb的內容是什麼? – pdoherty926

+0

添加了schema.rb @ pdoherty926 – nacon

回答

0

使用這種select_tag解決我的問題

<%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %> 

但停止工作,如果我禁用多個像

:multiple => false