Adding values from a column of a Ruby related entity

3

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 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 as I do to add up all product prices. I did so in 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 is not legal to put business rule in the view. Another thing I wanted when registering this value was updated as I select the products to add to the sale, I did it, but it does not 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 %>
    
asked by anonymous 01.08.2016 / 19:31

1 answer

1

You can use your own relationship to sum the values

sale.products.sum(:price)

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

link

link

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 %>
    
02.08.2016 / 04:09