RoR无法找到没有ID的主题

时间:2012-06-25 09:11:28

标签: ruby-on-rails rails-activerecord

我是新手RoR开发者。我陷入了一个问题。我正在尝试为可以创建主题的用户创建应用程序,而其他人可以在主题下发布他们的评论。这些主题由用户创建并在主页上列为列表。我几乎完成了这些主题。但是当我点击它们查看帖子时,我发现没有ID错误就找不到主题。

我猜我的错误是主题有两个索引id和user_id。 这是我的主题模型:

class Topic < ActiveRecord::Base
  attr_accessible :content, :title
  belongs_to    :user
  has_many      :posts
  validates :title, presence: true, length: { maximum: 140 }
  validates :content, presence: true
  validates :user_id, presence: true
  default_scope order: 'topics.created_at DESC'
end

我的帖子模型

class Posts < ActiveRecord::Base
  attr_accessible :content 
  belongs_to :topic
  belongs_to :user
  validates :user_id, presence: true
  validates :content, presence: true
  default_scope order: 'posts.created_at DESC'
end

这是我的topics_controller.rb:

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

    def show
        @topic = Topic.find(params[:id])
        @posts = @topic.posts.paginate :page => params[:page], :per_page => 20
    end
       .
       ..vs

这是我的config / routes.rb

MyPedia::Application.routes.draw do
    resources :users
    resources :sessions, only: [:new, :create, :destroy]
    resources :topics, only: [:show, :create, :destroy]
    resources :posts
    root to: 'static_pages#home'


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

    match '/help',    to: 'static_pages#help'
    match '/about',   to: 'static_pages#about'
    match '/contact', to: 'static_pages#contact'

我的主题show.html.erb

<% title @topic.title %>  
<div class ="center">
<h3><%= @topic.title %></h3>  

<% if @posts? %>  


  <% for post in @posts do %>  
    <p><strong><%= post.content %>  
  <% end %>  
<% end %>  
</div> 

我试图找到解决这个问题的方法。 谢谢你的帮助

3 个答案:

答案 0 :(得分:3)

尝试使用GET / topic / 1,这会有所帮助。您设置匹配路由的方式是错误的,可能是多余的。您可以在此处查看更多信息:http://guides.rubyonrails.org/routing.html

答案 1 :(得分:0)

虽然主题有宁静的路线,但在主题#的路线中显示没有:id

 match '/topicin',   to: 'topics#show'  # <===== :id is missing

也许这会导致问题。

答案 2 :(得分:0)

只需添加

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