【发布时间】:2014-05-26 17:54:00
【问题描述】:
我希望用户从订单表单中的项目表中搜索现有项目,它适用于客户但不适用于项目,它会给出错误:Association :item not found
型号
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
回答
在表格中使用: 使用 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
【问题讨论】:
-
为什么要添加
has_many :order_items和has_many :items, :through => :order_items?你应该只在 AFAIK 上添加第二个。 -
另外
belongs_to :user和belongs_to :client看起来很奇怪,用户实际上不是客户吗? -
我指的是:link 他们有 has_many,所以我想我也需要它
-
好吧,用户是为客户创建订单的员工。客户不接触系统。
-
啊哈,我明白了,那么关于关联逻辑一切都很好:)
标签: ruby-on-rails simple-form select2-rails