ruby-on-rails - Rails4 - 在订单表单中显示项目

标签 ruby-on-rails simple-form select2-rails

我希望用户从订单表单中的项目表中搜索现有项目,它适用于客户,但不适用于项目,它会给出错误:关联:找不到项目

型号

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/

相关文章:

ruby-on-rails - simple_form_for 失败, "can' t 写入未知属性 `builder'”

javascript - 使用 select2 迭代 Javascript 中的 ruby​​ 对象

ruby-on-rails - simple_form 'form-inline' 不工作

ruby-on-rails - 如何将 select2-rails 与acts_as_taggable_on (simple_form) 一起使用

javascript - 如何重置 select2 中的特定选定选项

ruby-on-rails - 如何使用回形针处理多种文件类型

ruby-on-rails - 接受嵌套属性和过滤器

ruby-on-rails - 在 Ubuntu 中安装 "rails"时出现问题

javascript - Rails 4 Turbolinks 未加载 MathJax

ruby-on-rails - 隐藏 bool 表单字段