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

Question:

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: [])
end

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

  <tbody>
    <% @sales.each do |sale| %>
    <tr>
      <td><%= sale.product.sum(:price) %></td>
      <td><%  sale.products.each do |product| %>
       <li> <%= link_to product.name, product_path(product)  %></li>
      <% end %></td>
      <%= sale.products.count %>
      <td><%= sale.client.name %></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>
    </tr>
    <% end %>
</tbody>

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>

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

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

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


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

Answer:

You can use the relationship itself to sum the values

sale.products.sum(:price)

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

http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html

http://railscasts.com/episodes/196-nested-model-form-part-1

example

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

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

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