我希望用户从订单表单中的项目表中搜索现有项目,它适用于客户,但不适用于项目,它会给出错误:关联:找不到项目
型号
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 %>
Controller
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
回答
在表单中使用: 使用rails-select2 gem
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, prompt: "Choose an item", input_html: { id: 'item-select2' } %>
或者没有选择2
<%= f.select :item_ids, Item.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
感谢 JKen13579
最佳答案
您收到 item
错误但未收到 client
错误的原因是,有一个 client
与订单关联,但与订单相关联的商品
不只一个。它说 :item not find
因为您应该使用 :items
(注意复数)。
要允许对订单
的商品
进行多项选择,请将您的f.association item
行替换为:
<%= f.select :item_ids, Item.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
然后在您的 Controller 中,确保允许 item_ids
。此外,您不需要 item_attributes
,因为您没有使用 accepted_nested_attributes_for :items
。
def order_params
params.require(:order).permit(:code, :client_id, :user_id, :memo, :status, item_ids: [])
end
参见this SO answer有关 has_many
:through
多选的更多信息。
关于ruby-on-rails - Rails4 - 在订单表单中显示项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23875464/