我的问题是更多地了解资源和路由。我跟着 ruby on rails 教程书开始定制我的应用程序。在我的应用程序中,我想让用户发送帖子,其他人通过发送照片来讨论该主题。我创建用户没有任何问题。在主页中,我想按日期显示所有用户的帖子。主题模型是
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 Post < 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
和迁移是:
create_table "topics", :force => true do |t|
t.string "title"
t.text "content"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
end
add_index "topics", ["user_id", "created_at"], :name => "index_topics_on_user_id_and_created_at"
我的主题控制器:
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
这是我的路线.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/:id', to: 'topics#show'
我的 show.html.erb 是
<div class ="center">
<h3><%= @topic.title %></h3>
<% if @posts %>
<% for post in @posts do %>
<p><strong><%= post.content %>
<% end %>
</div>
<%end %>
我的 rake 路由表是这样的:
topics POST /topics(.:format) topics#create
topic GET /topics/:id(.:format) topics#show
DELETE /topics/:id(.:format) topics#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
.我可以在主页中看到我的主题作为链接列表,没有任何问题。当我点击它们时,我希望它们向我展示主题和其中的帖子。当我使用 localhost:3000 这就是我现在得到的。
No route matches {:action=>"show", :controller=>"topics", :id=>#<Topic id: nil, title: nil, content: nil, created_at: nil, updated_at: nil, user_id: 1>}
当我使用 localhost:3000/topics/1
SQLite3::SQLException: no such column: posts.topic_id: SELECT "posts".* FROM "posts" WHERE "posts"."topic_id" = 1 ORDER BY posts.created_at DESC LIMIT 20 OFFSET 0
所以我阅读了说明,但我找不到直接使用主题的方法。抱歉,问题太长了。这将帮助我理解许多关于导轨的问题。
编辑 1:我在帖子表中添加了 topic_id ... static_pages 控制器是:
class StaticPagesController < ApplicationController
def home
@topic = current_user.topics.build if signed_in?
@topics = Topic.paginate :page => params[:page], :per_page => 20
end
错误在 _topics.html.erb 中:
<% for topic in @topics do %>
!!!!! <li><%=link_to topic.title, topicin_path(@topic) %></li>
<%= will_paginate @topics %>
<% end %>