'Adding an attribute to json from joined table
I am trying to provide a json that would contain information coming from two tables:MenuItem, and Partner.
In the json below "partner_number" would actually come from the partner table.
{
"id": 33,
"partner_id": 12,
"partner_number":234526,
"item_price": "15.0",
"item_type": "Main-meal",
"name": "Teriyaki Chicken Donburi",
"description": "Three eggs with cilantro, tomatoes, onions, avocados and melted Emmental cheese. With a side of roasted potatoes, and your choice of toast or croissant."
},
This is the method I built, trying to add the information into the results.
def index
@menu_items = policy_scope(MenuItem).joins(:partner)
@menu_items.each do|item|
item[:partner_number] = item.partner.partner_number
end
end
But it gives me this error message
ActiveModel::MissingAttributeError in Api::V1::MenuItemsController#index
can't write unknown attribute partner_number
Is there a way to do it from the controller ?
Solution 1:[1]
join method not load relationships into results. You should use includes who make a join AND load relationships
@menu_items = policy_scope(MenuItem).includes(:partner)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alexandre-rousseau |
