How to add values from a column in Ruby / RoR

1

Beauty?

I'm trying to build an application in Rails. I have a feature where users report the runtime related to a category . Well, I need to add up the total time in the runtime column to be able to show to a particular user: "You've already performed a total of X hours of activity" .

Another point is that I made the relationship with the Category model with the category_id attribute and everything is working fine, but I'd like to make it appear on the form through a list of categories (by name) and not have the user type the category id to make the relationship.

    
asked by anonymous 08.04.2014 / 01:06

1 answer

1

Sum and other aggregation functions

To sum values through the API ActiveRecord , use the sum() . Example:

Person.sum('age')

List of options

On the second point, to display a select (Combo Box) element and make it easier to select, you can use collection_select . Example taken from the guide item 3.3 :

<%= collection_select(:person, :city_id, City.all, :id, :name) %>

In the above passage:

  • :person is a reference to model
  • :city_id is the attribute that makes the relationship
  • City.all is the list of possible relationship values
  • :id is the value of each item in the list (the :id selected will be assigned to :city_id )
  • :name is the label to be displayed in the combo for each item

Update

The value of the field may not be updating in the model. A probable cause is not having defined the attribute as accessible.

Rails 3 Example:

class Item < ActiveRecord::Base
  attr_accessible :category_id

Example rails 4:

class ItemsController <  ApplicationController
  def item_params
    params.require(:item).permit(:category_id)
  end
    
08.04.2014 / 17:53