0

抱歉标题搞砸了,但我什至不知道如何正确解释我的问题..

我有一个带有“total_price”字段的预订表单的rails应用程序。表单可以通过cocoon gem https://github.com/nathanvda/cocoon (ajax) 房间模型添加/删除房间 有一个字段“价格”。

如何根据房间数量和他们选择的类型更新字段 total_price ?

预订/new_html.erb

   <%= simple_form_for @reservation do |f| %>
   <%= f.error_notification %>
<fieldset>
  <%= f.input :date_from, as: :string, input_html: { class: 'date', id: 'checkin',  :placeholder   => 'From' }, :label => false %>

  <%= f.input :date_to, as: :string, input_html: { class: 'date', id: 'checkout', :label => false %>

  <div id="rooms">
    <%= f.fields_for :entries do |entry| %>
        <%= render 'entry_fields', :f => entry %>
    <% end %>

    <%=  link_to_add_association 'add room', f, :entries %>
  </div>

  <%= f.input :total_price, :label => false %>
</fieldset>

<%= f.button :submit %>
<% end %>

预订/_entry_fields.html.erb

<div class="nested-fields">
  <div class="field">
    <%= f.association :rooms, input_html: { class: 'room-select' },  :label => false %>
    <%= f.number_field :number_of_rooms, input_html: { class: 'room-count' }, :label => false %>
    <%=  link_to_remove_association "Remove room", f %>
  </div>
</div>

预订控制器

class ReservationsController < ApplicationController
    def new
        @reservation = Reservation.new
    end
    def create
     @reservation = Reservation.new(reservation_params)
     if @reservation.save

      redirect_to root_path, :notice => "Booking Confirmed"
    else
      render "new"
    end
  end

  private
    def reservation_params
    params.require(:reservation).permit(:date_to, :date_from,  entries_attributes: [ :reservation_id, :number_of_rooms, :_destroy, :room_ids => []])
  end
end

我的 apps/assets/javascript/application.js 是空的,除了 jquery 和 cocoon

Cocoon 确实支持回调,但我非常有限的 JS 知识无法提出解决方案。

任何指导将不胜感激, 感谢您的时间

4

1 回答 1

0

Well, afaik the total-price does not change when you add a new room, it changes when you select the room or the number of rooms (I am assuming that selecting a room actually selects a type).

So you can use simple jquery for that.

And when you dynamically remove a room, then the total price changes, and you should use the cocoon:after_remove callback for that.

Recap:

  • when .room-select or .room-count receives a change event --> recalculate total price
  • when cocoon:after-remove event is triggered --> recalculate total price
于 2014-06-25T22:44:19.890 回答