form_for嵌套资源中的路由

时间:2012-06-26 09:02:12

标签: ruby-on-rails routing

我正在尝试完成一个用户可以打开主题的应用程序,其他用户可以使用帖子进行评论。我将我的资源嵌套在routes.rb中:

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.html.erb中为=&gt;

undefined method `model_name' for NilClass:Class

Extracted source (around line #1):

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

1 个答案:

答案 0 :(得分:1)

您的控制器的show动作中没有@post变量(仅@posts)。

尝试添加:

@new_post = @topic.build_post

并将表单更改为:

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