后端Controller计算逻辑转CoffeeScript的正确性验证与调用咨询
Step-by-Step Solution to Migrate Calculation to Client-Side CoffeeScript
Let's fix your code to replicate the original Ruby logic exactly, handle form submission client-side, and display results in the modal without hitting the backend.
1. Corrected CoffeeScript Code
Your existing CoffeeScript had issues with element selection, function syntax, and missing edge cases. Here's the fixed version that mirrors your Ruby controller logic:
$ -> # Cache DOM elements for efficiency savingsForm = $('#savings-form') savingsModal = $('#savings_modal') monthsDisplay = $('#months-to-buy') savingsDisplay = $('#total-savings') # Core calculation function matching Ruby logic calculateSavings = (priceInput, mortgageInput, rentInput) -> # Clean and parse input values (remove commas for numeric conversion) parseValue = (val) -> if val?.trim() then parseFloat(val.replace(/,/g, '')) else null price = parseValue(priceInput) mortgage = parseValue(mortgageInput) rent = parseValue(rentInput) if price? && mortgage? && rent? monthlySavings = mortgage - rent # Avoid division by zero or negative savings scenarios if monthlySavings <= 0 monthsToBuy = 24 totalSavings = "great savings" else savingsGoal = price * 0.03 monthsToBuy = Math.floor(savingsGoal / monthlySavings) totalSavings = monthlySavings * monthsToBuy # Format as currency for better user experience totalSavings = "$#{totalSavings.toLocaleString()}" else # Fallback values if inputs are incomplete monthsToBuy = 24 totalSavings = "great savings" { monthsToBuy, totalSavings } # Handle form submission savingsForm.on 'submit', (e) -> e.preventDefault() # Stop the form from posting to the backend # Get raw input values price = $('#house_amount').val() mortgage = $('#high_rent').val() rent = $('#current_rent').val() # Run calculation results = calculateSavings(price, mortgage, rent) # Update modal content with results monthsDisplay.text(results.monthsToBuy) savingsDisplay.text(results.totalSavings) # Show the modal savingsModal.modal('show')
Key fixes made:
- Uses
getElementById(via jQuery$()) instead ofgetElementsByNameto correctly access input values - Adds input cleaning to handle commas in numeric entries
- Includes edge case handling for zero/negative monthly savings (prevents division by zero)
- Formats total savings as currency for readability
- Wraps logic in a document-ready handler to ensure DOM is loaded before running
2. Updated ERB Form & Modal
Adjust your ERB code to remove backend dependencies and add dynamic placeholders for results:
<%= form_tag '#', id: 'savings-form', class: 'your-form-classes' do %> <span class="questions"> <!-- Fixed duplicate ID to class --> <h5 class="label">Estimated home cost?</h5> <%= text_field(:amount, {id: "house_amount", placeholder: "ex. 100,000"}, class: "form-control form-control-lg") %> </span> <span class="questions"> <h5 class="label">Estimated payment</h5> <%= text_field(:high_rent, {id: "high_rent", placeholder: "ex. 1,200"}, class: "form-control form-control-lg") %> </span> <span class="questions"> <h5 class="label">Current Monthly Rent?</h5> <%= text_field(:current_rent, {id: "current_rent", placeholder: "ex. 800"}, class: "form-control form-control-lg") %> </span> <%= submit_tag("See how quickly you can buy a home", class: "btn btn-success btn-lg") %> <% end %> <!-- Modal for sign-up --> <div class="modal" id="savings_modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <h3 class="modal-title" id="savingsModalTitle">You could be ready to buy in <span id="months-to-buy">24</span> months</h3> <h5 class="modal-title">and have <span id="total-savings">great savings</span>* to put down</h5> <div class="modal-body"> <h4>Sign-up Now to get started!</h4> <%= render '_tenant_signup_modal_form.html.erb' %> </div> </div> </div> </div>
Key changes:
- Removed
remote: trueand backend action from the form tag (we're handling submission client-side) - Added an ID (
savings-form) to the form for easy selection in CoffeeScript - Replaced duplicate
id="questions"with a class (duplicate IDs are invalid HTML) - Added
<span>placeholders with IDs (months-to-buyandtotal-savings) to inject calculated results - Removed data-toggle attributes from the submit button (we show the modal manually in CoffeeScript)
3. How It Works
- When the user submits the form, the CoffeeScript intercepts the submission and prevents the default backend POST.
- It cleans and parses the input values, runs the calculation matching your original Ruby logic.
- It updates the modal's dynamic content with the results.
- Finally, it triggers the modal to display to the user.
This setup fully replicates your original backend logic on the client-side, providing a faster user experience without server round-trips.
内容的提问来源于stack exchange,提问作者SupremeA
相关产品推荐
相关产品推荐

