0

我是新手 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> 

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

4

3 回答 3

3

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

于 2012-06-25T09:21:06.587 回答
0

虽然主题有 restful 路由,但在 topic#show 的路由中没有:id

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

也许这是造成问题的原因。

于 2012-06-25T09:15:00.883 回答
0

只需添加

 match '/topicin/:id',   to: 'topics#show'
于 2012-06-25T09:26:00.613 回答