ruby-on-rails - 试图了解何时使用嵌套路由与何时不使用
问题描述
我有以下型号:
class Blog < ApplicationRecord
has_many :posts
end
class Post < ApplicationRecord
belongs_to :blog
end
现在我只有两条路线:
/blogs/:blog_id/posts
- 创建一个帖子/posts/id:
- 更新帖子
我不确定是否应该将第二个更改为也接受: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
我的问题是:可以做我正在做的事情,还是一种不好的做法?
谢谢你。
解决方案
我不确定这个答案是否更像是一种观点,但我会说是的——保持简单。
要创建帖子,您需要一个:blog_id
嵌套资源是一种方法。其他将是POST /post
并传递:blog_id
POST 参数。
两者看起来都很好,由你来设计你的 API。最大的规则:保持一致。
话虽如此 - 我不记得我正在使用的单个 API,它使用嵌套资源来创建/更新方法。看起来很尴尬:如果我创建一个帖子 - 为什么它的一个属性 ( blog_id
) 应该进入路径,而其余的应该作为参数发送?
另一方面,嵌套资源非常适合读取方法:
/post/1/comments
而不是/comments?post_id=1
是更自然的落到了它身上——访问资源/post/1
和子资源作为子路径/post/1/author
,/post/1/tags
但是直接创建资源POST /tags
,post /comments
将属性作为参数传递。
推荐阅读
- haskell - 确定第一个参数的列表是否包含第二个参数列表中的元素
- c# - 如何在 AutoFixture 中使用一个自定义对象创建对象列表?
- kotlin - 需要从序列中过滤行但将其保留为单个序列
- angular-cli - 为什么 Angular CLI 在我运行 ng serve 时会显示 sourceMappingUrl?
- python-3.x - 当用户按下回车键时,python 脚本中的“输入”函数在终端中显示回车符 (^M)
- python - 在python中比较两个列表的索引的方法
- html - 使 div 中的 div 与该行中最大的 div 大小相同
- wordpress - Woocommerce 进出口 - 虚拟产品
- python-3.x - Python - 在 Pandas df 中使用 scipy 函数的结果创建一个新字段
- javascript - 在正在循环的数组内的特定索引中插入项目