首页 > 解决方案 > 试图了解何时使用嵌套路由与何时不使用

问题描述

我有以下型号:

class Blog < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :blog
end

现在我只有两条路线:

我不确定是否应该将第二个更改为也接受:blog_id. update 方法(在控制器上)不需要使用站点来更新帖子:

class PostsController < ApplicationController
  before_action :set_site, only: [:create]
  before_action :set_post, only: [:update]

  PERMITED_POST_PARAMS = [
    :post_id,
    :title,
    :url,
    :body
  ].freeze

  def create
    @post = @site.posts.build(post_params)

    if @post.save
      render json: @post, status: :created
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  def update
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  private

  def post_params
    params.require(:post).permit(*PERMITED_POST_PARAMS)
  end

  def set_post
    @post = Post.find(id)
  end

  def set_site
    @site = Site.find(site_id)
  end

  def post_id
    params[:post_id]
  end

  def id
    params[:id]
  end
end

我的问题是:可以做我正在做的事情,还是一种不好的做法?

谢谢你。

标签: ruby-on-railsruby

解决方案


我不确定这个答案是否更像是一种观点,但我会说是的——保持简单。

要创建帖子,您需要一个:blog_id嵌套资源是一种方法。其他将是POST /post并传递:blog_idPOST 参数。

两者看起来都很好,由你来设计你的 API。最大的规则:保持一致。

话虽如此 - 我不记得我正在使用的单个 API,它使用嵌套资源来创建/更新方法。看起来很尴尬:如果我创建一个帖子 - 为什么它的一个属性 ( blog_id) 应该进入路径,而其余的应该作为参数发送?

另一方面,嵌套资源非常适合读取方法: /post/1/comments而不是/comments?post_id=1

是更自然的落到了它身上——访问资源/post/1和子资源作为子路径/post/1/author/post/1/tags

但是直接创建资源POST /tagspost /comments将属性作为参数传递。


推荐阅读