This is a beginner’s question but for some reason I cannot find the answer elsewhere.
Customer has_many orders
Order has_many order_items
I am in customer/show.html.erb and I want my customer to manipulate order_items.
Many orders have many order_items and I want to search ALL of those order_items to find those such that read == false.
#controller
@customer = Customer.find(params[:id])
@orders = @customer.orders
@order_items = @orders.order_items doesn’t work. Given that I have multiple items in @orders, how can I collect all the order_items that belong to @orders?
=== EDIT ===
My entire database structure is a big complicated group of tables and I need to traverse that tree for this particular view.
customer has_many orders
orders has_many order_items
order_items belongs_to category
How do I, for example, find the number of my customer’s order_items that belong to category X?
Last question: why doesn’t @orders.find_all_by_x(…) work?
1) Show all OrderItems for a customer
You can add a relation called “order_items” to your customer like this:
You can then do:
To find all the unread OrderItems (where read == false), you can add a named_scope to your OrderItem:
you can then find all unread OrderItems for one customer by:
2) Show all OrderItems of a Customer belonging to a given Category
Again, a named scope in OrderItem (I assume OrderItem belongs_to Category):
Two Notes:
You have to include :category in the conditon
even though its belongs_to :category (singular), you have to use :categories (plural). This is because the :include adds the table as plural. (I don’t know why it does that, and for me this seems like a hint that this is not the best solution.)
This does work as expected for me. What error message are you getting?