【问题标题】:Rails - show item price and add to total priceRails - 显示商品价格并添加到总价中
【发布时间】:2014-05-27 07:23:59
【问题描述】:

我有一个表单,它在 select2 下拉框中显示项目,但我还想显示项目的价格并输入将显示总价的数量。使用带有这些附加功能的 select2 gem 会很好,但我不知道该怎么做。

我必须知道选择了哪个项目,然后从表中提取价格。

表格

<%= simple_form_for(@order) do |f| %>
  <%= f.error_notification %>
    <%= f.input :code %>    

    <%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, prompt: "Choose an item", input_html: { id: 'item-select2' } %>
    <%= f.submit %>
<% end %>

塔布

  create_table "items", force: true do |t|
    t.string   "name"
    t.decimal  "price"
    t.integer  "quantity"
    t.decimal  "discount"
  end
  create_table "orders", force: true do |t|
    t.string   "code"
    t.integer  "user_id"
  end
  create_table "order_items", force: true do |t|
    t.integer  "item_id"
    t.integer  "order_id"
    t.integer  "quantity"
    t.decimal  "price"
  end

【问题讨论】:

  • 你的项目是私有的?或者我可以在github上找到它?
  • 很难理解 select2 应该是什么样子。是多选吗?
  • 是多选,带搜索的下拉选择框
  • 即使没有select2,我该怎么办?

标签: ruby-on-rails simple-form


【解决方案1】:

您必须使用 AJAX。 假设我们有一个表单 (order),其中我们有一个表 (order_items)。我们将添加包含一些好东西(items)、它们的价格和数量的行。假设用户已经打开了新订单并添加了新行。在行中,我们将选择项目、跨度 price 和文本字段 quantity。在表下我们有跨度total

  1. 用户选择项目。当项目被选中时,我们为此选择调用“on_change”javascript 事件。
  2. 在该调用中,我们向项目控制器(方法“显示”)发送了 AJAX 请求,并带有所选项目的 ID。在控制器#show 中,我们找到了我们的项目并将其以 json 格式返回给客户端。
  3. 在客户端,我们有一个 javasript 对象 item。使用 javascript,我们将 item.price 放在 span price 内。
  4. 我们必须为数量文本字段调用另一个“on_change”。当数量改变时,我们迭代所有行,计算每一行的总和并将其累积到结果变量中。然后我们把这个结果放在 total 跨度中。

【讨论】:

  • 类似于this? 的东西与表单集成?
  • 是的,不用Angular也能搞定,这里jQuery就够了。
  • 如何将 AJAX 请求发送到项目控制器(方法显示)并选择 id(基本上是 #2)
  • app/assets/javascripts/application.js: $('#select_with_goodies').on('change', function(){ $.get('items_controller/' + $('#select_with_goodies ').val()); }); app/views/items/show.js // 根据接收到的数据更新表单
猜你喜欢
  • 2020-12-15
  • 2013-11-29
  • 2014-05-02
  • 2020-04-23
  • 2021-11-16
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多