从Ruby on Rails类获取belongs_to关系

时间:2018-03-27 07:06:25

标签: activerecord active-model-serializers ruby-on-rails-5.2

以下是我的模特:

class OrderItem < ApplicationRecord
   belongs_to :order
   belongs_to :product
end

class Order < ApplicationRecord
   has_many :order_items
end

这是我的控制器:

def index
    orders = Order.where(nil)
    render json: {'orders': orders}, include: 
    ['order_items'], status: :ok
end

我想在order_items中包含该产品。如何获得以下JSON:

    {
        "id": 2,
        "order_items": [
            {
                "id": 1,
                "product": {
                    "name": "abc"
                },
            }
        ]
    },

2 个答案:

答案 0 :(得分:0)

您可以通过更改来达到此目的 include: ['order_items']include: ['order_items', 'order_items.product']

您可以获得更多详细信息here

答案 1 :(得分:0)

我已经能够通过将include: {'order_items': {include: 'product'}}更改为 @IBAction func sliderAction(_ sender: UISlider) { speed = round(sender.value / step) * step sender.value = speed speedLabel.text = modeDict[sender.value] print(sender.value) print(speedLabel.text) } let modeDict : [Float : String] = [ 0.8 : "Pls delete game, you noob", 0.9 : "Pff, girl", 1.0 : "Optimal", 1.1 : "Very Hard", 1.2 : "Almost Unreal"] let step : Float = 0.1 var speed : Float = 0.0 //

来解决此问题