代码之家  ›  专栏  ›  技术社区  ›  mayorsanmayor

Angular 2前端与Rails 5 API中的活动记录关联

  •  0
  • mayorsanmayor  · 技术社区  · 9 年前

    请帮助我在Rails中有一个API应用程序,它的很大一部分依赖于活动记录关联,我想了解如何在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
    

    和一个项目。rb模型文件

    class Project < ApplicationRecord
      belongs_to  :category
    end
    

    我已经能够从角度前端实现与API的通信。在rails视图(erb或haml)文件中,如果我想获取项目的类别,我可以使用@Project.category

    使用上面的代码结构,如何使用我在 project.ts 文件 如何在项目中使用Category_id访问类别的名称和所有其他属性。ts?由于呈现的JSON对象仅具有category_id,因此下面的示例对我不起作用。。。

    *ngFor = "let project of projects" 
    project.category_id.name 
    

    关于如何解决这个问题有什么想法吗?

    我能够使用ActiveModelSerializer将category name属性获取到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}}时,它不起作用。

    1 回复  |  直到 9 年前
        1
  •  0
  •   halfer Jatin Pandey    4 年前

    在验证前端有一个JSON对象后,我才能够让它工作。这是我的类别。ts文件现在看起来像这样。角管非常有用, check here 阅读更多关于他们的信息。

    export class Category {
      constructor(
      public id?: number, 
      public name?: string
     ) {}
    }
    
    let category: Category = JSON.parse('{"id": id, "name": name}');
    

    Had还必须验证类别名称是否适用于前端的所有项目

    <small *ngIf="project.category">Category: {{ project.category.name }}</small>​
    

    如果您想知道我的ProjectsController索引是什么样子的,请看这里。另外,不要忘记创建category_serializer和project_serial。请查看ActiveModelSerializer文档了解如何创建。

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