How to add values from a column in Ruby/Ror

Asked

Viewed 796 times

1

Loveliness?

I’m trying to build an application in Rails. In it I have a resource where users inform the running time related to a category. Well, I need to perform adding up the total column time running time in order to present to a particular user: "You have already performed a total of X hours of activities".

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

1 answer

1


Sum and other aggregation functions

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

Person.sum('age')

List of options

On the second point, to display an element select (Combo Box) and facilitate selection, you can use the collection_select. Example taken from section 3.3 of the guide:

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

In the above section:

  • :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 combo for each item

Updating

The field value may not be being updated in the template. A probable cause is not having defined the attribute as accessible.

Example Rails 3:

class Item < ActiveRecord::Base
  attr_accessible :category_id

Example Rails 4:

class ItemsController <  ApplicationController
  def item_params
    params.require(:item).permit(:category_id)
  end
  • Hello @utluiz, thank you so much for your help! I’m having a little problem in the list of options, in my case the relationship is by category, so I did: <%= collection_select(:person, :category_id, Category.all, :id, :name) %>, but when submitting the form it informs that the Category field cannot be empty, even though I have selected a category. How should I do? PS.: I forgot to mention that I’m starting at Ror.

  • @user5476 I will update the response with some suggestions of what may be.

  • All right then. Fighting for help!

  • I analyzed the log and see that it is not saving due to the same person. Then I tried to adjust in the controller but it did not work params.require(:exercice).permit(:timer, :date, { person: [:category_id] })

  • Thank you @utluiz! Your help was essential. Hug!

  • @user5476 Glad you could. I’m sorry I didn’t answer more, but it was all going on at work. Hug.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.