【发布时间】:2016-12-27 10:25:35
【问题描述】:
请帮助我在 Rails 中有一个 API 应用程序,它的很大一部分依赖于 Active Record 关联,我想了解如何在我的 Angular 2 前端应用程序上使用 Rails API 呈现的活动记录模型之间的关系。例如:
我有一个带有
的 project.ts 文件export class Project {
constructor( public id?: number,
public title?: string,
public category_id?: number
) {}
}
还有一个带有
的 category.ts 文件export class Category {
constructor(
public id?: number,
public name?: string
) {}
}
也是一个 category.rb 模型文件,带有
class Category < ApplicationRecord
has_many :projects
end
还有一个 project.rb 模型文件
class Project < ApplicationRecord
belongs_to :category
end
我已经能够从 Angular 前端实现与 API 的通信。在 Rails 视图(erb 或 haml)文件中,如果我想获取项目的类别,我会做 @project.category
使用上面的代码结构,如何使用 project.ts 文件中的 category_id 获取项目的类别名称实例? 如何使用 project.ts 中的 category_id 访问类别的名称和所有其他属性?因为呈现的 JSON 对象只有 category_id,所以下面的这个例子对我不起作用......
*ngFor = "let project of projects"
project.category_id.name
关于如何解决这个问题的任何想法?
我能够使用 ActiveModelSerializer 将类别名称属性导入 JSON 对象,我的对象现在看起来像这样。
[
{
"category": {
"id": 1,
"name": "Mobile Development"
},
"category_id": 1,
"description": "Contrary to popular belief, Lorem Ipsum is not simply random text. \n It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.",
"id": 22,
"title": "Project 9 Test",
"updated_at": "2016-12-23T05:30:05.098Z"
},
]
当我尝试从前端访问 {{ project.category }} 时,我得到 [object Object] {{ project.category_id }} 返回一个有效的 ID,知道如何访问 name 属性吗?当我尝试 {{ project.category.name }} 时它不起作用。
【问题讨论】:
-
我试过了,我得到了类别 ID,仍然无法从 rails 获得类别名称... {{ project.category_id }}
标签: ruby-on-rails api angular activerecord