0

我正在编写一个应用程序,用户可以创建主题,其他人可以在该主题上发表帖子。

我被这个错误困住了:

No route matches {:action=>"show", :controller=>"topics", :id=>nil}

我的 route.rb :

MyPedia2::Application.routes.draw do
    resources :users

    resources :sessions, only: [:new, :create, :destroy]
    resources :topics, only: [:show, :create, :destroy] 

  match '/signup',  to: 'users#new'
  match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete

    root to: 'static_pages#home'

    match '/topics/:id', to: 'topics#show'

我的耙子路线显示:

   topics POST   /topics(.:format)         topics#create
      topic GET    /topics/:id(.:format)     topics#show
            DELETE /topics/:id(.:format)     topics#destroy
    root        /                         static_pages#home
               /topics/:id(.:format)     topics#show

我的主题控制器是:

# encoding: utf-8

class TopicsController < ApplicationController
    before_filter :signed_in_user, only: [:create, :destroy]
  before_filter :correct_user, only: :destroy


  def show
        @topic = Topic.find_by_id(params[:id])
  end

    def create
        @topic = current_user.topics.build(params[:topic])
        if @topic.save
            flash[:success] = "Konu oluşturuldu!"
            redirect_to root_path
        else
            render 'static_pages/home'
        end
    end

  def destroy
    @topic.destroy
    redirect_to root_path
  end
  private

    def correct_user
      @topic = current_user.topics.find_by_id(params[:id])
      redirect_to root_path if @topic.nil?
    end
end

有解决办法吗?编辑:我发现 _topics.html.erb 失败了我发现是什么破坏了代码:

<% for topic in @topics do %>  
  <li><%=link_to topic.title, topic_path(@topic) %></li>  

 <%= will_paginate @topics %>
<% end %>  

topic_path(@topic] 部分是错误的。我怎样才能让它使用 id?

4

4 回答 4

1

它不起作用,因为您的收藏是“@topics”,每个元素都是“topic”,而不是“@topic”。但你很接近。试试这个:

<li><%=link_to topic.title, topic_path(topic) %></li>  
于 2012-06-26T00:43:08.930 回答
0

经过数小时的思考,现在我可以看到我的错误了。我在主题控制器中使用了 show 方法,但我的视图/主题中没有 show.html.erb。

如果你想展示你的主题,你必须使用这些方法:

1) 在 config/routes.rb 中使用:

match '/topics/:id', to: 'topics#show'

2) 在我使用的模型中,belongs_to :user,:foreign_key => "user_id"

3)链接为:

<li><%=link_to topic.title, **topic_path(topic)** %></li> 

4)并准备您在路线中提到的模板。

我希望这对任何人都有帮助。

于 2012-06-25T23:44:01.050 回答
0

试试这个:

<li><%=link_to topic.title, topic_path(:id => @topic.id) %></li>  
于 2012-06-26T00:32:09.387 回答
0

我认为您的路线可能应该是:

resources :sessions, :only => [:new, :create, :destroy]
resources :topics, :only => [:show, :create, :destroy]
于 2012-06-26T01:33:15.897 回答