Sort records from types Rails

Hi im trying to sort output data without the controller in the layout, im using devise, formtastic and some other gems to make the login and user interface

the problem is that i have 3 tables Products, Carted_products and Users, and i want to show the Carted_products by Product_id in the view, i got already it to show them by record in the table but i want it to SORT them example:

I have 3 different orders, 2 of them have the same product_id, they have each:

  1. Ammount
  2. Product_id
  3. User_id

and i can acces the price via carted_product.product in the model asociation

heres my view code:

%tbody

     - if user_signed_in?
       - current_user.carted_products.each do |f|
         - @total = @total + f.carted_product_price(f.ammount, f.product.price)
         %tr
           %td.carted_name
             = f.product.name
           %td.carted_ammount
             = f.ammount
           %td.carted_price  
             $ 
             = f.carted_product_price(f.ammount, f.product.price)

carted_product_price just recieves the ammount and price of the product and returns the multiplied price

so it prints all the rows in the table it doesnt matter if the different records are form the same product, i just want to join them in only one table row output

Answers


I think you want to iterate through the products, not the carted products. Personally, I'd move most of this logic to the model.

class Product
  ...
  def carted_products_total_amount
    carted_products.inject(0) {|acc, amount| acc + amount }
  end

  def total
    carted_product_price(carted_products_total_amount, price)
  end
end

And then in the view:

%tbody
   - current_user.products.each do |product|
     - @total = @total + product.total
     %tr
       %td.carted_name
         = product.name
       %td.carted_amount
         = product.carted_products_total_amount
       %td.carted_price  
         $ 
         = product.total

Also, the correct spelling of "amount" only includes a single "m" character. ;)


Need Your Help

DataGridView not being created

c# winforms visual-studio-2010 datagridview mouseclick-event

I have a datagridview with a clickevent assigned to it. This datagridview is on a tabpage. When the user clicks the datagridview, I want a second datagridview to be created below it. This is the co...