I have an AR association with extensions in Rails similar to the example presented in this link:
ActiveRecord Association Extensions
has_many :issues, :through => :qbert_issues do
def tracking
where("qbert_issues.kind = ?", "tracking")
end
def blocking
where("qbert_issues.kind = ?", "blocking")
end
end
As shown above, mine is multi-typed… I need to populate a ‘kind’ column in my join table. Ideally, this should just work:
q = QBert.find(123)
q.issues.tracking << Issue.find(234)
So, what the article suggests is overloading << and doing something like this:
has_many :issues, ... do
...
def <<(issue)
issue.kind = "UserAccount"
proxy_association.owner.issues += [issue]
end
end
Which would be nice, if kind was static.
It looks like I can do this…
has_many :issues, ... do
...
def <<(*args)
issue, kind = args.flatten
issue.kind = kind
proxy_association.owner.issues += [issue]
end
end
Which would allow me to do this at the very least:
q = QBert.find(123)
q.issues.tracking << [Issue.find(234), :tracking]
That doesn’t seem very DRY to me…is there a better way? Bonus points if you take into account that the kind accessor is off a join table qbert_issues. I’m guessing I just have to add the association manually through the QBertIssue model directly.
Figured it out…
Which lets me do:
It could be made sufficiently generalized by parsing out the
where_valuesand merging them into the parameters hash.Pryrocks, by the way 😀