带有jquery和计算服务器端的动态表单

时间:2016-07-03 22:03:40

标签: javascript jquery ruby-on-rails json

我有一个rails应用程序,可以使用表单生成报价以租用会议室。每个报价需要从数据库中的不同模型(房间,费率)中提取的一些输入以及特定于每个报价(小时,附加)的一些其他输入,这些输入直接填入报价表。

利用所有数据,我在模型中运行一些计算,以获得特定日期特定会议室的价格。

我试图在表单旁边的同一页面上动态显示这些计算的结果。

为此,我有:

- >带有嵌套字段的表单。

<%= form_for(@quote) do |f| %>
  <%= f.text_field :hours, class: "form-control" calculation %>
  <%= f.text_field :extras, class: "form-control calculation" %>
  .
  .
  <%= f.fields_for :contact, @quote.contact do |contact_form| %>
    <%= contact_form.text_field :email, class: "form-control"%>
  <% end %>
  .
  .
  <%= f.fields_for :room, @quote.room do |room_form| %>
    <%= room_form.collection_select :room_id, Room.all, :id, :name, class: "form-control" %>
  <% end %>  
  .
  .
  .             
<%= f.submit class: "btn btn-default btn-primary" %>
<% end %>

- &GT; Quote模型中的一些逻辑

class Quote < ActiveRecord::Base
  belongs_to :contact
  belongs_to :client
  belongs_to :room
  has_one :booking
  belongs_to :rate
  accepts_nested_attributes_for :contact
  accepts_nested_attributes_for :booking

  validates :rate_id, presence: true
  validates :contact_id, presence: true
  validates :room_id, presence: true

def calculate_quote
    (half_day_price + 
     full_day_price + 
     extended_day_price + 
     hours_price) / 
     calculate_discount 
end

def calculate_discount
    if self.rate
        self.rate.discount_rate / 100
    else
        return 1
    end
.
.
.
end 

- &GT;控制器中的一个方法,它应该用这些计算的结果创建一个json响应。

class QuotesController < ApplicationController
before_action :set_quote, only: [:show, :edit, :update, :destroy, :pricing]

def pricing
    respond_to do |format|
        format.json { render json: @quote, methods: [:calculate_quote, :half_day_price], only: [:id, :calculate_quote, :half_day_price, :full_day_price] }
    end
end 
.
.
.

- &GT;一切都变成了参数

def quote_params
    params.require(:quote).permit(:half_days, :full_days, :extended_days, :extras, :rate, :discount, :rate_id, contact_attributes: [:id, :name, :email, :phone], booking_attributes: [:id, :start_date, :end_date, :start_time, :finish_time])
end

- &GT;还有一个应该从json中获取数据的js文件:

$(function(){
  $(".calculation").change(function(){
    var rate = $("#quote_rate_id").val();
    var room = $("#quote_room_room_id").val();
    var half_days = $("#quote_half_days").val();
    var full_days = $("#quote_full_days");
    var extended_days = $("#quote_extended_days");
    var extras = $("#quote_extras");
    var discount = $("#quote_discount");
    jQuery.getJSON(url? + "/pricing", { rate: rate, room: room,  half_days: half_days, full_days: full_days, extended_days: extended_days, hours: hours, extras: extras, discount: discounti}, function(data){
    $("#half-days-price").text(data.half_days);
    $("full-days-price").text(data.full_days);

    });
});
});

按照这种方法,我一直试图找到正确的路线和网址,让这个表单在引号/ new下工作,同时在json保存之前传递引号对象的id。这让我想知道,这是开始的正确方法吗?我应该遵循不同的道路吗?

我会很感激一些新鲜的想法。

0 个答案:

没有答案