简体   繁体   English

在导轨 7 中加载相关的 model

[英]Load related model in rails 7

I'm new in ruby rails and face some difficult to achieve something.我是 ruby 导轨的新手,面临一些难以实现的目标。 Now I have a product model:现在我有一个产品 model:

class Product < ApplicationRecord
belongs_to :category

And category model:和类别 model:

class Category < ApplicationRecord
    has_many :products

When I call the product like so: @products.inspect i wan to see the category belongs to the product.当我这样称呼产品时: @products.inspect我想查看属于该产品的类别。 My output now looks like so:我的 output 现在看起来像这样:

<ActiveRecord::Relation [#<Product id: 1, name: "Adidas", description: "Adidas is a Dutch multinational corporation that i...", price: 100, created_at: "2022-08-23 10:02:11.110159000 +0000", updated_at: "2022-08-23 10:02:11.114384000 +0000", category_id: 1>, #<Product id: 2, name: "asd", description: "12easd", price: 12, created_at: "2022-08-24 09:35:38.839809000 +0000", updated_at: "2022-08-24 09:35:38.847999000 +0000", category_id: 1>]>

Getting the product.category working fine, but, I need also the name of the category attached to this output.product.category正常工作,但是,我还需要附加到此 output 的类别名称。 I need this because the product is sent to a JavaScript function and I need to call the category name from there.我需要这个,因为产品被发送到 JavaScript function 并且我需要从那里调用类别名称。 What I already try is the follow:我已经尝试过的是:

def index
@products = Product.includes(:category).all
end

Thanks in advance.提前致谢。

I found it!我找到了!

@product.to_json(include: :category)

And now I get the related category model现在我得到了相关的类别 model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM