I’m still a newbie with Rails (and actually development period). I’m using Rails 3.
activity has these fields: id, user_id, activity_type (integer).
In my view, I want to show a count of each activity type the user has done, something like this:
<%= activity.activity_type %> - [count for activity]
Only, I can figure out how to do it. In my controller, I tried different things like:
@user = current_user
@activity_type_ids = Activity.select("DISTINCT(activity_type_id)")
@activity_type_counts = Activity.where('user_id = ? and activity_type_id = ?', @user.id, @activity_type_ids).count
or
@activity_type_counts = Activity.where('user_id = ? and activity_type_id = ?', @user.id, @activity_type_ids).group("activity_type_id").count
In my view, I’ve tried:
<% @activity_type_counts.each do |activity_type_count| %>
<%= "(#{activity_type_count.activity_type_id}) #{activity_type_count}" %>
<% end %>
and
<% @activity_type_ids.each do |activity_type_id| %>
<%= "(#{activity_type_id.activity_type_id}) #{@activity_type_count}" %>
<% end %>
Thank you in advance for any help you can provide!
updated with models and controller
fixing the model details
I have three models: user, location and activity. A user has many locations. A location can have many activities.
user.rb
has_many :locations
location.rb
belongs_to :user
has_many :activities
activities.rb
belongs_to :location
activity_report_controller
@user = current_user
@locations = @user.locations
@activities = @locations.activities.count(:group => "activity_type_id")
I assume you have
Then you can just say
This should return an
OrderedHashwith the keys as theids and the values as the counts.UPDATE: turns out the original question was wrong, there is an intermediary
LocationWhat you want is a has many through on user to activities
Now in your controller.