2012-06-26 71 views
1

我想完成一个应用程序,用户可以打开一个主题,其他用户可以使用Posts发表评论。我嵌套我的资源routes.rb中:form_for嵌套资源路由

resources :users 

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

resources :posts 

我耙路线显示:

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 

在我的主页,我建立主题的可点击列表,你可以打开一个话题一个文本。现在,如果您点击主题链接,我希望它向您显示在顶部显示主题名称的页面,下方的帖子和下方的帖子表单在同一页面中。 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.h中tml.erb为=>

undefined method `model_name' for NilClass:Class 

Extracted source (around line #1): 

1: <%= form_for([@topic, @post]) do |f| %> 

回答

1

你不必在你的控制器(仅@posts)的表演动作的@post变量。

尝试增加:

@new_post = @topic.build_post 

和改变形式:

<%= form_for([@topic, @new_post]) do |f| %>