rails中的路由错误

时间:2015-03-17 06:57:29

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我正在开展一个项目。我正在创建一个用户可以添加问题的应用程序(如帖子),用户可以对其进行评论。

在运行此应用程序时,出现错误 无法找到' id' = show 的问题 路由文件的代码是

 resources :issues do
    resources :comments
  end

  get 'users/new'

  get 'users/create'

  get 'users/show'

  get 'users/edit'

  get 'issues/show/:id', :to => 'issues#show'

  resources :users
  resources :sessions, :only => [:create, :new,:destroy]




  get '/signup', :to => 'users#new'
  get '/signin' , :to => 'sessions#new'
  get '/signout', :to => 'sessions#destroy'

问题控制器的代码是

class IssuesController < ApplicationController


    def new
        @issue = Issue.new
    end


    def create
        @issue = Issue.new(issues_params)
        if @issue.save
            flash[:success]='your issue has been raised'
            redirect_to :controller => 'issues', :action => 'show', :id => @issue.id 
        else 
            render 'new'
        end

    end

    def edit
        @issue = Issue.find(params[:id])

    end

    def update
        @issue = Issue.find(params[:id])
        if @issue.update_attributes(issues_params)
            redirect_to :controller => 'issues', :action => 'show', :id => @issue.id        
        else 
            render 'edit'
        end 
    end

    def index
        @issues = Issue.all

    end 


    def show

        @issue = Issue.find(params[:id])


    end

    def destroy
        @issue=Issue.find(params[:id])
        @issue.destroy
        redirect_to :controller => 'issues', :action => 'index'
    end








    protected
        def issues_params
        params.require(:issue).permit(:title,:content)
        end


end

我在调用控制器中调用show方法的注释控制器的代码是

class CommentsController < ApplicationController


def create 
    @issue = Issue.find(params[:issue_id])
    @comment = @issue.comments.create(comment_params)

    if @comment.save
        redirect_to :controller => 'issues', :action => 'show', :id => @issue[:id]
    else 
        render 'new'
    end
end 





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

    end


end

2 个答案:

答案 0 :(得分:1)

您必须尝试申请URI /issues/show吗?这会映射到您路线的GET /issues/:id行的resources :issues do。路由器会将params[:id]设置为字符串"show"并将请求发送到show的{​​{1}}操作,正如您所示,该操作会尝试执行IssuesController即。 Issue.find(params[:id])因此你得到了错误。

答案 1 :(得分:1)

更改此

resources :issues do
  resources :comments
end

resources :issues, except: [:show] do
  resources :comments
end

它将解决您的问题!