在Ruby on Rails框架中,为模型之间的归属关系(例如has_many和belongs_to)设置路由是一种常见的任务。以下是如何为这些关系设置路由的步骤:
Comment
可能属于一个Post
。User
有一个Profile
。Post
有多个Comment
。Student
可以选修多个Course
,反之亦然。假设我们有两个模型:Post
和Comment
,其中Post
has_many
Comments
,而Comment
belongs_to
Post
。
# app/models/post.rb
class Post < ApplicationRecord
has_many :comments
end
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
在config/routes.rb
文件中,你可以使用resources
方法来定义嵌套路由。
# config/routes.rb
Rails.application.routes.draw do
resources :posts do
resources :comments, only: [:index, :new, :create, :edit, :update, :destroy]
end
end
这将生成以下路由:
GET /posts/:post_id/comments
- 显示特定帖子的所有评论GET /posts/:post_id/comments/new
- 创建新评论的表单POST /posts/:post_id/comments
- 创建新评论GET /posts/:post_id/comments/:id/edit
- 编辑特定评论的表单PUT/PATCH /posts/:post_id/comments/:id
- 更新特定评论DELETE /posts/:post_id/comments/:id
- 删除特定评论# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
before_action :set_post
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def index
@comments = @post.comments
end
def new
@comment = @post.comments.new
end
def create
@comment = @post.comments.new(comment_params)
if @comment.save
redirect_to post_comments_path(@post), notice: 'Comment was successfully created.'
else
render :new
end
end
def edit
end
def update
if @comment.update(comment_params)
redirect_to post_comments_path(@post), notice: 'Comment was successfully updated.'
else
render :edit
end
end
def destroy
@comment.destroy
redirect_to post_comments_path(@post), notice: 'Comment was successfully destroyed.'
end
private
def set_post
@post = Post.find(params[:post_id])
end
def set_comment
@comment = @post.comments.find(params[:id])
end
def comment_params
params.require(:comment).permit(:content)
end
end
原因:可能是路由定义错误,或者在控制器中没有正确设置before_action
回调来加载相关的Post
或Comment
。
解决方法:
config/routes.rb
文件中的路由定义是否正确。before_action
回调来加载必要的资源。rails routes
命令查看生成的路由列表,确认是否符合预期。通过以上步骤,你可以有效地为Rails应用中的归属关系设置路由,并处理常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云