我正在尝试完成一个应用程序,用户可以打开一个主题,其他用户可以用帖子发表评论。我将资源嵌套在 routes.rb 中:
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :topics, only: [:show, :create, :destroy] do
resources :posts
我的 rake 路线显示:
topic_posts GET /topics/:topic_id/posts(.:format) posts#index
POST /topics/:topic_id/posts(.:format) posts#create
new_topic_post GET /topics/:topic_id/posts/new(.:format) posts#new
edit_topic_post GET /topics/:topic_id/posts/:id/edit(.:format) posts#edit
topic_post GET /topics/:topic_id/posts/:id(.:format) posts#show
PUT /topics/:topic_id/posts/:id(.:format) posts#update
DELETE /topics/:topic_id/posts/:id(.:format) posts#destroy
topics POST /topics(.:format) topics#create
topic GET /topics/:id(.:format) topics#show
在我的主页中,我构建了一个可点击的主题列表和一个可以打开主题的文本区域。现在,如果您单击主题链接,我希望它向您显示顶部显示主题名称的页面,下面的帖子和同一页面下的帖子表单。显示.html.erb:
<div class="row">
<div class="span6 offset4">
<h3><%= @topic.title %></h3>
<h4><%= render 'shared/posts'%></h4>
<%= render 'shared/post_form' %>
</div>
</div>
</div>
我的posts_controller 是:
# encoding: utf-8
class PostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
before_filter :correct_user, only: :destroy
def new
@topic= Topic.find_by_id(params[:id])
@post = @topic.build_post
end
def show
@topic = Topic.find(params[:id])
@posts = @topic.posts.paginate(page: params[:page])
end
def create
@topic = Topic.find(params[:id])
@post = @topic.posts.build(params[:post])
if @post.save
flash[:success] = "Konu oluşturuldu!"
redirect_to root_path
else
render 'static_pages/home'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def correct_user
@post = current_user.posts.find_by_id(params[:id])
redirect_to root_path if @post.nil?
end
end
和 _posts.html.erb :
% @posts.each do |post| %>
<li><%= post.content %></li>
<%= will_paginate @posts %>
<% end %>
_post_form.html.erb :
<%= form_for([@topic, @post]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "yorumunuzu girin..." %>
</div>
<%= f.submit "Gönder", class: "btn btn-large btn-primary" %>
<% end %>
错误在 _post_form.html.erb as =>
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for([@topic, @post]) do |f| %>