- has_many :through, but dynamic 660 days ago
-
Speaking of Rails, I’ve used a neat tecnique that I’d like to share. I don’t know if this is the best solution for my problem but it could be, well, at least “original” :)
I need to associate many Person that work in my Project. I save this relation as a Contribution giving each person a role. From an ActiveRecord point of view this is a classic has_many :through relation.
Every person has a role, within the Project and I’d like to add people to the project with a simple “<<” operator as in Project.find(:first).architect << People.find(1). Then I’d like to get all the “designers” with a simple Project.find(:first).designers.
The problem is that I have MANY roles, so I’d end up declaring a ugly lot of (complex) has_many associations. How could I DRY them?
I solved sticking this “oneliner” in my Project model:
PERSON_ROLES.each do |role| has_many role.to_s.pluralize.to_sym, :through => :contributions, :source => :person, :conditions => ["contributions.role = ?", role.to_s] do def <<(person) Contribution.with_scope(:create => {:role => @reflection.name.to_s.singularize}) { self.concat person } end end end
Comments
commenting closed for this article
→ 61648624
→

