Ruby on rails 使用嵌套模型放置Rails
在我的Rails 5.1 API应用程序中,我有如下Ruby on rails 使用嵌套模型放置Rails,ruby-on-rails,active-model-serializers,Ruby On Rails,Active Model Serializers,在我的Rails 5.1 API应用程序中,我有如下Post和Comment模型 发布 class Post < ApplicationRecord has_many :comments end class Comment < ApplicationRecord belongs_to :post end 更新: 我正在从Angular 2客户端添加Post模型。Post模型将Comment[]作为成员之一。当通过表单添加新注释时,在将整个对象发送到Rails AP
Post
和Comment
模型
发布
class Post < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
end
更新:
我正在从Angular 2客户端添加Post
模型。Post
模型将Comment[]
作为成员之一。当通过表单添加新注释时,在将整个对象发送到Rails API后端之前,comment
被推送到post.comments
数组
在客户端发布
模型
import { Comment } from './comment';
export class Post {
id: number;
title: string;
text: string;
date: string;
comments: Comment[];
}
export class Comment {
comment: string;
date: string;
}
注释
客户端模型
import { Comment } from './comment';
export class Post {
id: number;
title: string;
text: string;
date: string;
comments: Comment[];
}
export class Comment {
comment: string;
date: string;
}
您可以使用
接受来自Post模型的注释的嵌套属性。如果将注释属性作为嵌套属性传递,而不使用id参数,则将创建新记录。如果您使用现有id传递它,则现有记录将相应更新
class Post < ApplicationRecord
has_many :comments
accepts_nested_attributes_for :comments
end
Rails为此提供了一个很好的文档显示您的帖子表单/post/:id
中的表单供用户输入评论。我已经从Angular 2客户端添加了Post
和Comment
模型-希望这能涵盖它。我厌倦了这种方法-但是新的评论仍然没有保存。在这里发布rails服务器控制台日志-您可以查看此问题,其中有更多详细信息-
def post_params
params.require(:post).permit(:id, :title, ... ,
comments_attributes: [:id, :comment] # Provide comment model attributes here]
)
end