Rails перебирает вставленную переменную из базы данных в URL для внешнего вызова
Я пытаюсь показать line_items заказа из Solidus в таблицу Items в моем приложении rails. Ранее я сохранял заказы из Solidus в своей таблице "Заказ" (в моем приложении) с атрибутом "номер_порядка"
Мне нужно вставить order_number в URL, который я использую для внешнего вызова с использованием httparty, и перебрать все строки в order_number, чтобы отобразить атрибуты каждого заказа в моем представлении индекса. Каждый заказ, например: http://localhost:4000/api/orders/R984044507.json?token=fd5a8b4b294303ad52fcb19a9eaf8bb7325d20a8aa5abbc7 имеет такую структуру:
{
"id": 3,
"number": "R984044507",
"item_total": "59.97",
"total": "68.22",
"ship_total": "5.0",
"state": "complete",
"adjustment_total": "3.25",
"user_id": null,
"created_at": "2017-07-09T17:12:19.209Z",
"updated_at": "2017-07-09T17:14:24.657Z",
"completed_at": "2017-07-09T17:14:24.657Z",
"payment_total": "0.0",
"shipment_state": "pending",
"payment_state": "balance_due",
"email": "ignaciosm@gmail.com",
"special_instructions": null,
"channel": "spree",
"included_tax_total": "0.0",
"additional_tax_total": "3.25",
"display_included_tax_total": "$0.00",
"display_additional_tax_total": "$3.25",
"tax_total": "3.25",
"currency": "USD",
"covered_by_store_credit": false,
"display_total_applicable_store_credit": "$0.00",
"order_total_after_store_credit": "68.22",
"display_order_total_after_store_credit": "$68.22",
"total_applicable_store_credit": "0.0",
"display_total_available_store_credit": "$0.00",
"display_store_credit_remaining_after_capture": "$0.00",
"canceler_id": null,
"display_item_total": "$59.97",
"total_quantity": 3,
"display_total": "$68.22",
"display_ship_total": "$5.00",
"display_tax_total": "$3.25",
"token": "vQyNyoZEdjOux5XYOCdafg",
"checkout_steps": [],
"payment_methods": [],
"bill_address": {},
"ship_address": {},
"line_items": [
{
"id": 3,
"quantity": 1,
"price": "19.99",
"variant_id": 17,
"variant": {
"product_id": 3,
"id": 17,
"name": "Ruby on Rails Baseball Jersey",
"sku": "ROR-00008",
"price": "19.99",
"weight": "0.0",
"height": null,
"width": null,
"depth": null,
"is_master": false,
"slug": "ruby-on-rails-baseball-jersey",
"description": "Fuga quia cumque sunt dignissimos eum unde dicta doloribus. Iste sit inventore doloribus et aut eum totam nisi. Ut quas explicabo omnis eos ipsa consequuntur. Aut a quis molestiae reprehenderit suscipit expedita.",
"track_inventory": true,
"cost_price": "17.0",
"option_values": [
{
"id": 3,
"name": "Large",
"presentation": "L",
"option_type_name": "tshirt-size",
"option_type_id": 1,
"option_type_presentation": "Size"
},
{
"id": 7,
"name": "Blue",
"presentation": "Blue",
"option_type_name": "tshirt-color",
"option_type_id": 2,
"option_type_presentation": "Color"
}
],
"images": [
{
"id": 15,
"position": 1,
"attachment_content_type": "image/png",
"attachment_file_name": "ror_baseball_jersey_blue.png",
"type": "Spree::Image",
"attachment_updated_at": "2017-07-08T23:10:54.595Z",
"attachment_width": 240,
"attachment_height": 240,
"alt": null,
"viewable_type": "Spree::Variant",
"viewable_id": 17,
"mini_url": "/spree/products/15/mini/ror_baseball_jersey_blue.png?1499555454",
"small_url": "/spree/products/15/small/ror_baseball_jersey_blue.png?1499555454",
"product_url": "/spree/products/15/product/ror_baseball_jersey_blue.png?1499555454",
"large_url": "/spree/products/15/large/ror_baseball_jersey_blue.png?1499555454"
},
{
"id": 16,
"position": 2,
"attachment_content_type": "image/png",
"attachment_file_name": "ror_baseball_jersey_back_blue.png",
"type": "Spree::Image",
"attachment_updated_at": "2017-07-08T23:10:55.123Z",
"attachment_width": 240,
"attachment_height": 240,
"alt": null,
"viewable_type": "Spree::Variant",
"viewable_id": 17,
"mini_url": "/spree/products/16/mini/ror_baseball_jersey_back_blue.png?1499555455",
"small_url": "/spree/products/16/small/ror_baseball_jersey_back_blue.png?1499555455",
"product_url": "/spree/products/16/product/ror_baseball_jersey_back_blue.png?1499555455",
"large_url": "/spree/products/16/large/ror_baseball_jersey_back_blue.png?1499555455"
}
],
"display_price": "$19.99",
"options_text": "Size: L, Color: Blue",
"in_stock": true,
"is_backorderable": true,
"total_on_hand": 9,
"is_destroyed": false
},
"adjustments": [
{
"id": 5,
"source_type": "Spree::TaxRate",
"source_id": 1,
"adjustable_type": "Spree::LineItem",
"adjustable_id": 3,
"amount": "1.0",
"label": "North America 5.000%",
"promotion_code": null,
"eligible": true,
"created_at": "2017-07-09T17:13:56.297Z",
"updated_at": "2017-07-09T17:14:24.280Z",
"display_amount": "$1.00"
}
],
"single_display_amount": "$19.99",
"display_amount": "$19.99",
"total": "20.99"
},
{
"id": 4,
"quantity": 1,
"price": "19.99",
"variant_id": 6,
"variant": {
"product_id": 6,
"id": 6,
"name": "Ruby Baseball Jersey",
"sku": "RUB-00001",
"price": "19.99",
"weight": "0.0",
"height": null,
"width": null,
"depth": null,
"is_master": true,
"slug": "ruby-baseball-jersey",
"description": "Fuga quia cumque sunt dignissimos eum unde dicta doloribus. Iste sit inventore doloribus et aut eum totam nisi. Ut quas explicabo omnis eos ipsa consequuntur. Aut a quis molestiae reprehenderit suscipit expedita.",
"track_inventory": true,
"cost_price": "17.0",
"option_values": [],
"images": [
{
"id": 34,
"position": 1,
"attachment_content_type": "image/png",
"attachment_file_name": "ruby_baseball.png",
"type": "Spree::Image",
"attachment_updated_at": "2017-07-08T23:11:04.206Z",
"attachment_width": 495,
"attachment_height": 477,
"alt": null,
"viewable_type": "Spree::Variant",
"viewable_id": 6,
"mini_url": "/spree/products/34/mini/ruby_baseball.png?1499555464",
"small_url": "/spree/products/34/small/ruby_baseball.png?1499555464",
"product_url": "/spree/products/34/product/ruby_baseball.png?1499555464",
"large_url": "/spree/products/34/large/ruby_baseball.png?1499555464"
}
],
"display_price": "$19.99",
"options_text": "",
"in_stock": true,
"is_backorderable": true,
"total_on_hand": 9,
"is_destroyed": false
},
"adjustments": [
{
"id": 6,
"source_type": "Spree::TaxRate",
"source_id": 1,
"adjustable_type": "Spree::LineItem",
"adjustable_id": 4,
"amount": "1.0",
"label": "North America 5.000%",
"promotion_code": null,
"eligible": true,
"created_at": "2017-07-09T17:13:56.327Z",
"updated_at": "2017-07-09T17:14:24.300Z",
"display_amount": "$1.00"
}
],
"single_display_amount": "$19.99",
"display_amount": "$19.99",
"total": "20.99"
},
{
"id": 5,
"quantity": 1,
"price": "19.99",
"variant_id": 7,
"variant": {
"product_id": 7,
"id": 7,
"name": "Apache Baseball Jersey",
"sku": "APC-00001",
"price": "19.99",
"weight": "0.0",
"height": null,
"width": null,
"depth": null,
"is_master": true,
"slug": "apache-baseball-jersey",
"description": "Fuga quia cumque sunt dignissimos eum unde dicta doloribus. Iste sit inventore doloribus et aut eum totam nisi. Ut quas explicabo omnis eos ipsa consequuntur. Aut a quis molestiae reprehenderit suscipit expedita.",
"track_inventory": true,
"cost_price": "17.0",
"option_values": [],
"images": [
{
"id": 33,
"position": 1,
"attachment_content_type": "image/png",
"attachment_file_name": "apache_baseball.png",
"type": "Spree::Image",
"attachment_updated_at": "2017-07-08T23:11:03.616Z",
"attachment_width": 504,
"attachment_height": 484,
"alt": null,
"viewable_type": "Spree::Variant",
"viewable_id": 7,
"mini_url": "/spree/products/33/mini/apache_baseball.png?1499555463",
"small_url": "/spree/products/33/small/apache_baseball.png?1499555463",
"product_url": "/spree/products/33/product/apache_baseball.png?1499555463",
"large_url": "/spree/products/33/large/apache_baseball.png?1499555463"
}
],
"display_price": "$19.99",
"options_text": "",
"in_stock": true,
"is_backorderable": true,
"total_on_hand": 9,
"is_destroyed": false
},
"adjustments": [
{
"id": 7,
"source_type": "Spree::TaxRate",
"source_id": 1,
"adjustable_type": "Spree::LineItem",
"adjustable_id": 5,
"amount": "1.0",
"label": "North America 5.000%",
"promotion_code": null,
"eligible": true,
"created_at": "2017-07-09T17:13:56.337Z",
"updated_at": "2017-07-09T17:14:24.313Z",
"display_amount": "$1.00"
}
],
"single_display_amount": "$19.99",
"display_amount": "$19.99",
"total": "20.99"
}
]
}
вот мой контроллер:
# items controller
def index
order_number = 'R984044507' # just to test until I figure out how to loop through order_ids
url = 'http://localhost:4000/api/orders/'
key = '.json?token=fd5a8b4b294303ad52fcb19a9eaf8bb7325d20a8aa5abbc7'
response = HTTParty.get(url+order_number+key)
@items = response.parsed_response
end
Мой индекс выглядит так:
<table>
<thead>
<tr>
<th>Order</th>
<th>Variand_Id</th>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% (@items['line_items']).each do |item| %>
<tr>
<td><%= @items['number'] %></td>
<td><%= item['variant']["id"] %></td>
<td><%= item['variant']["name"] %></td>
<td><%= item['variant']['price'] %></td>
<td><%= item["quantity"] %></td>
</tr>
<% end %>
</tbody>
</table>
Я жестко запрограммировал номер заказа одного из заказов в своей таблице "Заказы", чтобы проверить, что он показывает элементы в каждом заказе, но я не знаю, как циклически просматривать заказы, чтобы получать элементы из каждого заказа.
Я не уверен, что мой подход лучший, я новичок. Любая помощь будет оценена.
1 ответ
Вы могли бы сделать что-то вроде этого:
контроллер
def index
orders = Order.all.pluck(:number)
@items = []
orders.each do |order|
order_number = order
url = 'http://localhost:4000/api/orders/'
key = '.json?token=fd5a8b4b294303ad52fcb19a9eaf8bb7325d20a8aa5abbc7'
response = HTTParty.get(url+order_number+key)
@items << response.parsed_response
end
end
Сначала вы получаете все номера заказов (я предполагаю, что number
это имя столбца в orders
таблица), а затем вы перебираете их, запрашивая каждый заказ и добавляя его атрибуты @items
массив.
Посмотреть
<table>
<thead>
<tr>
<th>Order</th>
<th>Variand_Id</th>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @items.each do |item| %>
<% item['line_items'].each do |line_item| %>
<tr>
<td><%= item['number'] %></td>
<td><%= line_item['variant']["id"] %></td>
<td><%= line_item['variant']["name"] %></td>
<td><%= line_item['variant']['price'] %></td>
<td><%= line_item["quantity"] %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
поскольку @items
это массив, который вам понадобится итерировать, поэтому необходимы два цикла: один для @items
и один для line_items
,
Хотя это решение должно работать, обратите внимание, что запрос большого количества заказов может вызвать проблемы с производительностью.