Hi
I have three tables groups,user_groups and contacts… user_group
table contains fields contact_id,group_id
Now i have to findout the contacts .I have the groupid
(params[:group_id].So at first from user_groups get all the contact_id
based on this group_id and after that from contacts table get all that
contacts…That is my requirement…How can i d this with pagination
also.(will_paginate)…I have done pagination for two tables joining…But
this is a little bit different…Please help me
Considering you have a Contact Model, you can add a class method in it
like so
class self.find_contacts_for_a_group(group_id,page)
paginate(:all, :conditions => [‘user_groups.group_id=?’, group_id],
:joins => “as contacts inner join
user_groups as user_groups on user_groups.contact_id=contacts.id”,
:page => page,
:per_page => 20)
end
and in your controller, lets say you create a method called
show_contacts like so:
def show_contacts
Contact.find_contact_for_a_group(params[:group_id], params[:page])
end
Are you not creating a many to many with this table setup. In which
case, if you use the rails methods it will reduce the amount of
thinking you need to do to access the various relationships:
Unless I have misunderstood you:
class Group < ActiveRecord::Base
has_many :user_groups
has_many :contacts, :through=>:user_groups
end
class Contact < ActiveRecord::Base
has_many :groups, :through=>:user_groups
has_many :user_groups
end
class UserGroup < ActiveRecord::Base
belongs_to :group
belongs_to :contact
end
So that you can do
@group=Group.find(params[:group_id])
@[email protected](:page=>params[:page])
(if you don’t need @group, you could combine this into one line)
Although, that is 2 fetches from the database, I reckon that is easier
to see
Another option I’ve followed for a number of “index” views is to create
a database view that can hide the complexity of multiple joins behind a
single model.
In one view, users requested data from the current model, that model’s
parent, and the parent’s parent, and a summary off a child table.
The database view hides all that nastiness, even from rails, and keeps
the controller code clean as well.
Might be overkill in your case, but for bigger conglomerations of data,
it hurt to see all the SQL generated by rails.