【问题标题】:Angular 2 Frontend with Active Record Association in Rails 5 APIRails 5 API 中带有 Active Record 关联的 Angular 2 前端
【发布时间】: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


【解决方案1】:

在验证我在前端得到一个 JSON 对象后,我能够让它工作。这就是我的 category.ts 文件现在的样子。我希望这对其他人有帮助。 Angular Pipes 非常有用,请查看 here 以了解更多信息。

export class Category {
  constructor(
  public id?: number, 
  public name?: string
 ) {}
}

let category: Category = JSON.parse('{"id": id, "name": name}');

​还必须使用

验证前端中的所有项目都可以使用类别名称
<small *ngIf="project.category">Category: {{ project.category.name }}</small>​

如果您想知道我的 ProjectsController 索引是什么样的,这里就是。另外不要忘记创建 category_serializer 和 project_serializer 查看 ActiveModelSerializer 文档以了解如何执行此操作。

def index
  @projects = Project.order('created_at DESC')
  render json: @projects, include: 'category.name'
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多