ruby-on-rails – Sum values ​​from a column of a Ruby-related entity


I'm trying to build an application in Rails. In it I have a resource where the user registers products and sales. The relationship is too much for many, to pass an array of products to sales I did the following

def sale_params
    params.require(:sale).permit(:value, :client_id, :installments, product_ids: [])

I would like a tip how do I add up all product prices. I did it like this on the view

    <% @sales.each do |sale| %>
      <td><%= sale.product.sum(:price) %></td>
      <td><%  sale.products.each do |product| %>
       <li> <%= link_to, product_path(product)  %></li>
      <% end %></td>
      <%= sale.products.count %>
      <td><%= %></td>
      <td><%= sale.installments %></td>
      <td><%= link_to 'Show', sale %></td>
      <td><%= link_to 'Edit', edit_sale_path(sale) %></td>
      <td><%= link_to 'Destroy', sale, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    <% end %>

It worked but it's not nice to put a business rule in the view. Another thing I wanted when I was registering this value to be updated as I select the products to add to the sale, I did it like that, but it doesn't work.

<%= form_for(@sale) do |f| %>

    <div class="field">
      <%= f.label :value %>
      <%= f.text_field :value, :value => @sale.products.sum(:price) %>

   <div class="field">
     <%= f.label :client_id %>
     <%= :client_id, Client.all.collect {|c| [,]}, include_blank: true %>

    <%= f.label :products %>
    <% for product in Product.all %>
    <div >
      <%= check_box_tag "sale[product_ids][]",, @sale.products.include?(product) %>
     <%= %> -
     <%= product.price %>
  <% end %>

   <div class="field">
     <%= f.label :installments %>
     <%= f.text_field :installments %>

  <div class="row">
    <div class="span1 actions">
       <%= f.submit :class => 'btn btn-primary' %>
<% end %>


You can use the relationship itself to sum the values


To get these queries out of the view you have to learn to use feilds_for


<%= form_for(@sale) do |f| %>

<div class="field">
  <%= f.collection_select(:city_id, options_for_select(Client.all, :id, :name)) %>

  <%= f.fields_for :products do |product| %>
    <%= product.label :product %>
    <div >
    <%= product.collection_check_boxes :product_ids, Product.all, :id, %>
  <% end %>
Scroll to Top