I want to display all the projects in which a given team has a
product. The following code works, but isn’t there a better way?
Railsier? Better Practice?
#Models#
class Team < ActiveRecord::Base
has_many :products
has_many :funding_sources, :through=>:products
end
class Product < ActiveRecord::Base
belongs_to :funding_source
belongs_to :team
end
class FundingSource < ActiveRecord::Base
belongs_to :project
has_many :products
end
class Project < ActiveRecord::Base
has_many :funding_sources
has_many :products, :through=>:funding_sources
has_many :teams, :through=>:products #Can I do this?
end
#projects_controller.rb#
Goal: all the projects in which a team has a product.
GET /projects/by_team/team_id
GET /projects/by_team/team_id.xml/
def by_team
begin
@team = Team.find(params[:team_id])
rescue
@projects=Project.find(:all)
else
[email protected]
funding_ids = products.reduce([]){|items, product|
items.push(product.funding_source_id)}
fundings=FundingSource.find(:all, :select=>:project_id,:conditions=>[“id
IN (?)”, funding_ids.uniq])
project_ids = fundings.reduce([]){|items, funding|
items.push(funding.project_id)}
@projects = Project.find(:all, :conditions=>[“id IN (?)”,
project_ids.uniq])
end
respond_to do |format|
format.html #by_team.html.erb
format.xml { render :xml => @projects }
end
end
I can add some of the