在查询结果中添加另一列-Ruby on Rails协会

时间:2018-11-09 00:38:03

标签: ruby-on-rails activerecord associations

我有一个Product模型,可以在其中发出API请求,并将其显示为json格式。因此,当我编写控制器(例如Product.all)并呈现为json(呈现json:products)时,它完美地显示了所有列的所有Products。但是,有一个单独的价格表,我想在其中包含相同的价格,并与Json一起打印。 (将新列添加到查询结果中的行)。

类似于 Products.all.price_tables_products

我知道不可能发出这样的请求,而且,我只需要从price_tables_products中选择一行。例如(price_tables_products.last)。您知道最好的解决方案吗?

product.rb

class Product < ApplicationRecord
  has_many :price_tables_products
end

price_table_products.rb

class PriceTablesProduct < ApplicationRecord
  belongs_to :product
end

1 个答案:

答案 0 :(得分:1)

我不完全了解您的要求,但是您可以使用自定义序列化器执行几乎所有操作。您可以阅读有关ActiveModel序列化程序here的信息。

但是基本上,在您的产品控制器上,您要呈现产品的方法:

class ProductsController < ActionController::Base
  def index
    render json: Product.all, each_serializer: ProductSerializer
  end
end

然后,在您的app/serializers文件夹中保留序列化程序类

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :created_at, :updated_at, :prices

  def prices
    PriceTablesProduct.where(product_id: object.id)
  end
end

在序列化器类上,您可以添加所有想要执行的方法。甚至覆盖现有方法,以便以特定方式呈现它们。

您甚至可以使用众所周知的关键字has_manybelongs_to等来渲染相关模型。