我正在Rails 5中开发一个简单的发票应用程序
对于这个问题,我有2个模型。
引用
class Quote < ApplicationRecord
belongs_to :client, optional: true
has_many :quote_items, dependent: :destroy
accepts_nested_attributes_for :quote_items
end
和QuoteItem
class QuoteItem < ApplicationRecord
default_scope { order(:id, :item_order) }
belongs_to :quote
end
因为我在QuoteItem模型中具有作用域,所以可以基于item_order字段在erb中显示数据。
但是现在我需要在JSON中使用相同的数据来构建动态表。我的QuoteItem模型中的范围不适用于Jbuilder。
这是JSON格式:
#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
我的问题是如何使用“item_order” 字段而不是他的“id” 设置 json.quote_items 的排序顺序。
最佳答案
解决了。
json.quote_items do
json.array!(@quote.quote_items.sort_by{|o| o[:item_order]}) do |item|
json.id item.id
.....
end