Reputation: 1049
I have a rails 3.1.12 application, in which suppose i have a table A and in that i have some data and it is associated with table B with has_many relationship, i mean to say
class A < ActiveRecord::Base
has_many :B, :conditions => {:type => "B"}, :dependent => :destroy
has_many :c, :class_name => "B", :conditions => {:type => nil}, :dependent => :destroy
end
and in B's model i have :
class B < ActiveRecord::Base
belongs_to :A
end
and i have some data in my table C which is inherited from B
- **name** **amount**
- c1 10
- c2 20
- c3 5
- c1 4
- c2 15
and i want to display this duplicate items only one time something like:
But i don't have any idea how to get this, i have tried **group_by**
and uniq
methods but they are not working in my case.In my controller A on view action i have declare all this like:
class AsController < ApplicationController
def show
@a = A.find(params[:id])
@bs = @a.bs
@cs = @a.cs
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @a }
end
end
end
and In my view file i have called all these like:
<%= render :partial => "b_item_details", :collection => @bs %>
<%= render :partial => "c_line_item_details", :collection => @cs %>
I am sure some might faced such issue, any help would be thankful
Actually i want to display unique records i mean if c1 has 4 entries and c2 has 3 entries than while displaying i want to display c1 and c2 only once and their total should be total of all their entries (c1+c1+c3+c4)
Upvotes: 0
Views: 256
Reputation: 15736
Try:
@cs = @a.cs.group(:name).sum(:amount)
This should return you a hash of name, amount pairs, e.g.:
{ 'c1' => 14, 'c2' => 35, 'c3' => 5 }
See http://guides.rubyonrails.org/active_record_querying.html#sum
Upvotes: 2