I get this, but i don’t really like it because if you compare it with
how i do it in the sql example, i only use one query with joines to get
the results. In your examples you create a loop (iterator) which submits
multiple queries
so, if there is no other method, i think i’ll just use plain old mysql
I was convinced rails had a better method…
regards,
remco
Alex W. wrote:
Remco Hh wrote:
Hi,
I know i can do this:
if i have an ordeline i can do:
customername=orderline.order.customer.name
but can i also go the other way around?
lets say i have a customer and i want to get a hold of all orderlines
orderlines=customer.orders.orderlines would be great, but that doesn’t
work
is there a smart way to do this or do i have to use a plain sql query
like:
select customer from customers,orders,orderlines where
customer.customer_id=orders.customer_id and
orderline.order_id=order.order_id
the above doesn’t look very rails-like, thefore i am asking…
Remco
As long as your associations are set up properly, you sure can do that.
However not exactly the way you expect.
customer.orders returns an array of orders, and an array does not have a
‘orderlines’ method. You should access it like this instead
customer.orders.each do |order|
do_something_with(order)
order.orderlines.each do |ol|
do_something_else_with(ol)
end
end
Or if you really want all the orderlines from all orders for a customer
lumped together in one big array, you can do:
orderlines = []
costomer.orders.each do |order|
orderlines += order.orderlines
end
I get this, but i don’t really like it because if you compare it with
how i do it in the sql example, i only use one query with joines to get
the results. In your examples you create a loop (iterator) which submits
multiple queries
so, if there is no other method, i think i’ll just use plain old mysql
I was convinced rails had a better method…
regards,
remco
You can use eager loading to make so only one query is needed.
class Customer
has_many :orders, :include => :orderlines
end
This will put a LEFT OUTER JOIN in your SQL and fetch all associated
orderlines along with the orders. Then customer.order.first.orderlines
will not generate a query.
I get this, but i don’t really like it because if you compare it with
how i do it in the sql example, i only use one query with joines to get
the results. In your examples you create a loop (iterator) which submits
multiple queries
so, if there is no other method, i think i’ll just use plain old mysql
I was convinced rails had a better method…
regards,
remco
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.