首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Rails 5.2中,无法访问多态关联中的某些路由

是由于Rails默认的路由生成器无法正确处理多态关联的路由。这个问题可以通过手动定义路由来解决。

首先,我们需要在路由文件中手动定义多态关联的路由。假设我们有一个多态关联的模型叫做"Comment",它可以关联到不同的模型,比如"Post"和"Article"。我们可以按照以下方式定义路由:

代码语言:txt
复制
# routes.rb

resources :posts do
  resources :comments, only: [:index, :new, :create]
end

resources :articles do
  resources :comments, only: [:index, :new, :create]
end

上述代码中,我们分别为"Post"和"Article"模型定义了相应的路由。这样,我们就可以通过访问/posts/:post_id/comments/articles/:article_id/comments来访问多态关联中的某些路由。

接下来,我们需要在控制器中处理这些路由。假设我们有一个"CommentsController",我们可以按照以下方式定义相关的动作:

代码语言:txt
复制
# comments_controller.rb

class CommentsController < ApplicationController
  before_action :set_commentable

  def index
    @comments = @commentable.comments
  end

  def new
    @comment = @commentable.comments.new
  end

  def create
    @comment = @commentable.comments.new(comment_params)
    if @comment.save
      redirect_to @commentable, notice: 'Comment was successfully created.'
    else
      render :new
    end
  end

  private

  def set_commentable
    if params[:post_id]
      @commentable = Post.find(params[:post_id])
    elsif params[:article_id]
      @commentable = Article.find(params[:article_id])
    end
  end

  def comment_params
    params.require(:comment).permit(:content)
  end
end

上述代码中,我们通过before_action方法在执行相关动作之前先调用set_commentable方法来设置@commentable变量。根据路由中的参数,我们可以判断出当前关联的模型是"Post"还是"Article",然后找到相应的记录。

最后,我们需要在视图中使用这些路由。假设我们有一个"comments/index.html.erb"视图,我们可以按照以下方式使用路由:

代码语言:txt
复制
<!-- comments/index.html.erb -->

<% @comments.each do |comment| %>
  <p><%= comment.content %></p>
<% end %>

<%= link_to 'New Comment', new_polymorphic_path([@commentable, :comment]) %>

上述代码中,我们使用new_polymorphic_path方法来生成新评论的路由。这个方法会根据当前关联的模型自动选择正确的路由。

总结一下,在Rails 5.2中,无法访问多态关联中的某些路由可以通过手动定义路由、处理控制器和使用视图中的路由辅助方法来解决。这样,我们就可以正确地访问多态关联中的路由了。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券