我希望用户从订单表单中的项目表中搜索现有项目,它适用于客户但不适用于项目,它给出错误:关联:未找到项目
楷模
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :client
has_many :order_items
has_many :items, :through => :order_items
end
class Item < ActiveRecord::Base
has_many :order_items
has_many :orders, :through => :order_items
end
class OrderItem < ActiveRecord::Base
belongs_to :item
belongs_to :order
end
移民
class CreateOrderItems < ActiveRecord::Migration
def change
create_table :order_items do |t|
t.integer :item_id
t.integer :order_id
t.timestamps
end
add_index :order_items, [:item_id, :order_id]
end
end
看法
<%= simple_form_for(@order) do |f| %>
<%= f.error_notification %>
<%= f.association :client, collection: Client.all, label_method: :name, value_method: :id, prompt: "Choose a Client", input_html: { id: 'client-select2' } %>
<%= f.association :item, collection: Item.all, label_method: :name, value_method: :id, prompt: "Choose an item", input_html: { id: 'client-select2' } %>
<%= f.input :memo, label: 'Comments' %>
<%= f.submit %>
<% end %>
控制器
def new
@order = Order.new
end
def create
@order = Order.new(order_params)
@order.user_id = current_user.id
@order.status = TRUE
end
def order_params
params.require(:order).permit(:code, :client_id, :user_id, :memo, :status, items_attributes: [:id, :name, :price, :quantity, :status, :_destroy])
end
回答
在表格中使用: using rails-select2 gem
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, prompt: "Choose an item", input_html: { id: 'item-select2' } %>
或没有 select2
<%= f.select :item_ids, Item.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
感谢 JKen13579