[英]How should I update a resource that is fully depend on other resource
Let's say I have those two models:假设我有这两个模型:
class Post < ApplicationRecord
belongs_to :site
end
class Site < ApplicationRecord
has_many :posts
end
In order to create a post, I need to know the site id.为了创建帖子,我需要知道站点 ID。 Right now I have a route that points to PostsController#create
:现在我有一条指向PostsController#create
的路线:
post 'posts', to: 'posts#update'
Should I expect the user to send the site_id
in the body of the request?我应该期望用户在请求正文中发送site_id
吗?
# config/routes.rb
resources :sites do
resources :posts
end
This creates nested routes .这会创建嵌套路由。 Run $ rails routes
to see the routes created.运行$ rails routes
以查看创建的路线。
Should I expect the user to send the site_id in the body of the request?我应该期望用户在请求正文中发送 site_id 吗?
No. A nested route describes the relationship between the two resources.不会。嵌套路由描述了两个资源之间的关系。 Its very obvious by looking at the path that POST /sites/1/posts
will create a post belonging to a site.通过查看POST /sites/1/posts
将创建属于站点的帖子的路径,这一点非常明显。
It would be ok to pass a site id in the params if you are using shallow nesting and the user can change which site a post belongs to when updating.如果您使用浅嵌套,则可以在参数中传递站点 ID,并且用户可以在更新时更改帖子所属的站点。
# app/controllers/posts_controller.rb
class PostsController
before_action :set_site
before_action :set_post, only: [:show, :edit, :update]
# GET /sites/1/posts/1
def show
end
# GET /sites/1/posts
def index
@posts = @site.posts
end
# GET /sites/1/posts/new
def new
@post = @site.posts.new
end
# POST /sites/1/posts
def create
@post = @site.posts.new(post_params)
if @post.save
redirect_to @post
else
render :new
end
end
# PATCH|PUT /sites/1/posts
def update
if @post.update(post_params)
redirect_to @post
else
render :edit
end
end
# GET /sites/1/posts/edit
def edit
end
private
def set_site
@site = Site.includes(:posts).find(params[:site_id])
end
def set_post
@post = @site.posts.find(params[:id])
end
def post_params
params.require(:post).permit(:title) # ...
end
end
# app/views/posts/_form.html.erb
<%= form_for [@site, @post] do |f| %>
# ...
<% end %>
# app/views/posts/new.html.erb
<%= render partial: 'form' %>
# app/views/posts/edit.html.erb
<%= render partial: 'form' %>
When you put on your route resources: posts that creates the automatic routes to index, show, create, update and delete.当您放置路线资源时:创建自动路线以索引、显示、创建、更新和删除的帖子。 post 'posts' should point to 'posts#create'. post 'posts' 应该指向 'posts#create'。 put 'posts' points to 'posts#update'.将“posts”指向“posts#update”。
And yes, send the site_id in the body of the request是的,在请求正文中发送 site_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.