Need some opinions about the best way to go about this. I
know :include does something similar, though I’m not sure if thats
what I need.
I have a Users model which :has_many of several other models, we’ll
call them model1, model2, model3 for example.
As of right now I have something like this in my controller:
@result1 = User.model1
@result2 = User.model2
@result3 = User.model3
Now the various models that belong to User have various different
columns/attributes in them, but they do share a common attribute of a
time column.
For use in one of my view I want to, for example, combine @result1,
@result2 and @result3 in one main @results hash and order them all by
time. Then in my view I can do one simple loop such as:
for result in @results
result.attribute_from_model1
result.attribute_from_model2_that_isnt_in_model1
…
end
I suppose there is a way to do this with either a Ruby (zip?) hash
merging method or a single AR call/join. Any thoughts? Thanks.
Also I was thinking maybe a combo of :include and :join might work? I
can’t seem to get the syntax right.
The has_many collections aren’t hashes, they’re arrays. You can
concatenate arrays with a + like so:
for result in User.model1 + User.model2 + User.model3
…
end
If you’re worried about their sort order, you can sort them manually
with the Array#sort_by method.
Bryan,
Ah ok, arrays make them much easier to deal with. Thanks I’ll give
this a try.
On Mar 23, 4:21 pm, Bryan D. [email protected]
Marston A. wrote:
Need some opinions about the best way to go about this. I
know :include does something similar, though I’m not sure if thats
what I need.
I have a Users model which :has_many of several other models, we’ll
call them model1, model2, model3 for example.
As of right now I have something like this in my controller:
@result1 = User.model1
@result2 = User.model2
@result3 = User.model3
Now the various models that belong to User have various different
columns/attributes in them, but they do share a common attribute of a
time column.
For use in one of my view I want to, for example, combine @result1,
@result2 and @result3 in one main @results hash and order them all by
time. Then in my view I can do one simple loop such as:
for result in @results
result.attribute_from_model1
result.attribute_from_model2_that_isnt_in_model1
…
end
I suppose there is a way to do this with either a Ruby (zip?) hash
merging method or a single AR call/join. Any thoughts? Thanks.
@result = {}
[User.model1s, User.model2s, User.model3s].each { | arr | @result.merge
arr.index_by(&:time) }
… then… later on back at the farm:
@result.keys.sort.each {|key| pp @result[key] }
hope this helps…
ilan