嵌套路由和CRUD操作以及Rails中的附加值

我在rails api中通过关系创建了一个has_many。 我也使用嵌套路线。

我的模特如下;

class Author  :comments end class Post  :comments end class Comment < ActiveRecord::Base belongs_to :author belongs_to :post end 

我的路线如下;

 Rails.application.routes.draw do namespace :api, defaults: { :format => 'json' } do resources :posts do resources :comments end resources :authors end end 

所以我的目标是

  1. 注释是嵌套路由,以便我可以创建和显示post的注释
  2. 这里没有任何post的作者。 作者是评论所有者

我实现了概念并且几乎都在工作。 但我面临以下两个协会问题

  1. 如何在父创建时为关联表添加其他字段。 这里我的要求是在创建post时,我需要插入一个默认条目进行评论。 我的post控制器实现如下所示
 def create params = create_params.merge(:record_status => 1) @post = Post.new(params) @post.authors << Author.find(1) if @post.save render :show, status: :created end end def show @post = Post.find(params[:id]) end private def create_params params.permit(:name, :description, :author_id ) end 

这里我在请求json中传递author_id。 这需要在comments表中添加为author id。 现在我只是硬编码为1.我使用'<<'进行关联输入。 这是有效的,但我还需要包括另外两个字段:comments和:record_status。 再次:评论来自请求本身。

注意:这不是rails mvc应用程序。 这是rails api并输入为json。

  1. 当我使用嵌套路线显示评论时,我需要显示作者以及评论表中的评论。 我的评论控制器方法是;
 class Api::CommentsController  1, comments: { record_status: 1 }) end private def fetch_post @post = Post.find(params[:post_id]) end end 

在这里我得到了作者但在连词表’评论’中没有正确的评论

请帮我解决这些问题

对于第一个问题,您希望将posts_controller配置为接受注释的嵌套属性。 在控制器的开头添加此行:

 accepts_nested_attributes_for :comments 

有关此方法的更多详细信息,请查看文档 。

然后,您需要修改控制器允许的参数:

 def create_params params.permit(:name, :description, :author_id, comments_attributes: [ :author_id, :comments, :record_status ] ) end 

修改comments_attributes数组中列出的属性以匹配Comment模型的属性。

我不确定你在第二个问题中想要得到什么,但也许你只需要稍微查询一下:

 @comments = Comment.where(post_id: @post.id).includes(:author) 

以上内容将返回评论列表,包括评论作者。

Interesting Posts