Rails 5 Api和Angular 4活动记录关联(belongs_to和has_many)

时间:2018-02-02 09:02:14

标签: angular devise ruby-on-rails-5.1

我正在尝试使用rails 5 Api和Angular4作为前端开发SPA,我的设计和angular2-token工作正常,我的模型是用户和小说,我有一个问题,即使所有小说属于特定用户我在小说模型中有user_id参考,请点击这里新的。

新模型

class Novel < ApplicationRecord
  belongs_to :user
end

用户模型

class User < ActiveRecord::Base
  # Include default devise modules.
  has_many :novels
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :omniauthable
  include DeviseTokenAuth::Concerns::User
end

我的角度新颖组件

export class HomeComponent implements OnInit {
  userEmail:string;
  novels: Array<NovelService>;
  constructor(public authService:Angular2TokenService,
    public http: HttpClient) {
      http.get('http://localhost:3000/novels').
      subscribe((res : NovelService[])=>{
        this.novels = res;
      });
  }

2 个答案:

答案 0 :(得分:0)

user = User.find id

user = User.find_by email: 'email'

然后:

user.novels

Novel.where(user_id: user.id)

答案 1 :(得分:0)

为了使那些可能遇到类似问题的人受益,只需使用Active Model Serializer Here is the github link