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".
Solved.
json.quote_items do
json.array!(@quote.quote_items.sort_by{|o| o[:item_order]}) do |item|
json.id item.id
.....
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With