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

时间:2015-08-01 16:33:08

标签: ruby-on-rails ruby rails-activerecord rails-api nested-routes

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

我的模特如下;

class Author < ActiveRecord::Base
 has_many :comments
 has_many :posts, :through => :comments
end

class Post < ActiveRecord::Base
 has_many :comments
 has_many :authors, :through => :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. 评论是嵌套路线,以便我可以创建和显示帖子
  2. 中的评论   
  3. 这里不是任何帖子的作者。作者仅供评论所有者
  4. 使用   

我实施了几乎所有的概念。但我面临以下两个关联问题

  1. 如何在父级创建时为关联表添加其他字段。这里我的要求是在创建帖子时,我需要插入一个默认条目进行评论。我的创建后控制器实现如下
  2. 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.我使用'&lt;&lt;&lt;进入协会。这是有效的,但我还需要包括另外两个字段:comments和:record_status。再次:评论来自请求本身。

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

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

      这里我在连接表'评论'中找到了作者但没有正确的评论

      请帮我解决这些问题

1 个答案:

答案 0 :(得分:0)

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

accepts_nested_attributes_for :comments

检查documentation以获取有关此方法的更多详细信息。

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

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)

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

相关问题