我有問題,我不知道如何以正確的方式解決它。在我的前端應用程式中,我選擇了顯示所有產品的選項,因此我需要向我的 Rails API 發送請求。控制器具有發送所有產品的方法索引,但具有許多不同的屬性和關聯。我不認為向這個方法發送請求是個好主意,因為<select>我只需要產品名稱和 ID。例子:
ProductController.rb
def index
render json: @products, include: 'categories, user.company'
end
ProductSerializer.rb
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :desc, :weight, :amount, ...
belongs_to :user
has_many :categories
end
如您所見ProductSerializer,發送很多東西,這是預期的,但在 FE 應用程式中以不同的視圖顯示。在另一個頁面中,我只需要 id 和 name 屬性即可<select>。我知道我可以像這樣創建新的Serializer并添加if:
def index
render json: @product, each_serializer: ProductSelectSerializer and return if pramas[:select]
render json: @products, include: 'categories, user.company'
end
但我不確定Serializer只為一個請求創建新的是否是一個好主意,因為在更大的應用程式中可能會有很多這樣的情況。在我看來,這種ifin index 方法看起來也不太好,所以也許我應該為這個請求創建新方法,但是對于一個小請求來說值得嗎?有什么好的做法可以幫助妥善解決這種情況嗎?
uj5u.com熱心網友回復:
我建議你試試blueprinter。它是一個可以幫助您序列化資料的 gem,這個 gem 適合您的需求。
要創建 Blueprinter 的序列化程式,您可以在終端中運行以下命令:
rails g blueprinter:blueprint Product
創建序列化器后,您可以使用視圖定義不同的輸出:
class ProductBlueprint < Blueprinter::Base
identifier :id
view :normal do
field :product_name
end
view :extended do
fields :product_name, :product_price
association :user, blueprint: UserBlueprint
association :categories, blueprint: CategoryBlueprint
# this will take the association from your product's model and make sure you have created the CategoryBlueprint and UserBlueprint
end
end
定義視圖后,現在您可以在控制器中使用該視圖。在您的索引操作中,您可以使用此語法呼叫它。
def index
render json: ProductBlueprint.render_as_hash(@product, view: :normal) and return if params[:select]
render json: ProductBlueprint.render_as_hash(@products, view: :extended)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427217.html
