Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i set an Order in a Rail's Jbuilder JSON

Tags:

I'm developing an simple invoicing app in Rails 5

For this question I have 2 models.

Quote

class Quote < ApplicationRecord
  belongs_to :client, optional: true
  has_many :quote_items, dependent: :destroy
  accepts_nested_attributes_for :quote_items
end

And QuoteItem

class QuoteItem < ApplicationRecord
  default_scope { order(:id, :item_order) }

  belongs_to :quote
end

Because i have a scope in the QuoteItem model I can display the data in my erb based in the item_order field.

But now i need to use the same data in JSON for build a dynamic table. And the Scope in my QuoteItem model is not working with Jbuilder.

This is the JSON format:

#myapp/app/views/quotes/show.json.jbuilder

json.quote do
  json.partial! "quotes/quote", quote: @quote


json.quote_items do
  json.array!(@quote.quote_items) do |item|
    json.id item.id
    json.clave item.product.clave
    json.name item.name
    json.quantity item.quantity
    json.item_order item.item_order
    json.days item.days
    json.unit_price item.unit_price
    json.seguro item.seguro
    json.descuento item.descuento
    json.total item.total
end

end
end

My question is How can I set the sort order of json.quote_items with the "item_order" field instead of his "id".

like image 604
Hugo Armando Vilchis Avatar asked Jan 22 '17 04:01

Hugo Armando Vilchis


1 Answers

Solved.

json.quote_items do
  json.array!(@quote.quote_items.sort_by{|o| o[:item_order]}) do |item|
  json.id item.id
  .....
end
like image 120
Hugo Armando Vilchis Avatar answered Oct 05 '22 23:10

Hugo Armando Vilchis