In Ruby on Rails, how to get joined result by SQL?
It seems that if the query is
Product.find_by_sql("select * from products INNER JOIN order_entries ... ")
then the objects returns will be Product object开发者_如何学Gos, while
OrderEntry.find_by_sql("select * from products INNER JOIN order_entries ... ")
will return OrderEntry objects. Is there a way to return the joined result? The reason is one field in the Product as well as one field in the OrderEntry are needed from the final joined results. Thanks.
I'm not sure exactly what level of detail you're talking about, but generally when I've had to execute a Join this way, I can reference the joined fields directly from the resulting objects. For instance, in a project where a Customer can make several Reservations:
customer = Customer.first
=> #<Customer id:1 ...>
customer.date
=> NoMethod Error (this is a Reservation method)
but...
customer = Customer.find_by_sql("select * FROM customers INNER JOIN reservations ON customers.id = reservations.customer_id").first
=> #<Customer id:1 ...> #looks the same, but isn't
customer.date
=> "2010-12-24"
Why, I have no idea, but the object responds to the joined fields. I searched for a minute to figure out how to differentiate between a regular object and one with the joined fields attached, but couldn't figure it out. Sorry for the brevity in thought & response, but running late...
If you specify the column names (and they are not ambiguous) you can retrieve the attribute directly:
sql = "select products.name, order_entries.description \
FROM products INNER JOIN order_entries ON products.id=order_entries.product_id"
result_set = Product.find_by_sql(sql)
This returns an array of objects with only the selected columns. You can now use the column names without having to go through the association:
result = result_set.first
result.name # "Widget"
result.description # "Best seller!"
精彩评论