2012-06-26 76 views
0

我想創建一個應用程序,用戶可以創建一個主題,然後其他人可以創建主題。我嵌套我的資源,我的routes.rb:嵌套資源創建無法找到沒有ID的主題

MyPedia2::Application.routes.draw do 
    resources :users 

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

    resources :posts, only: [:create, :show, :new] 

    end 

在我演講的題目顯示頁面,我想告訴topic.title和sended郵電post.form.html.erb。 一切正常接受,當我創建一個帖子,我得到的錯誤

ActiveRecord::RecordNotFound in PostsController#create 

Couldn't find Topic without an ID.. 

這是我posts_controller.rb:

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.posts.build(params[: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]) 
     @post.topic = @topic 

     if @post.save 
      flash[:success] = "Konu oluşturuldu!" 
      redirect_to :back 
     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 

和_post_form.html.erb:

<%= form_for @new_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 %> 

回答

1

有一些事情應該爲你解決問題。

首先,在posts控制器的create動作是有點不對勁 - 它應該是這個樣子:

def create 
    @topic = Topic.find(params[:topic_id]) 
    @post = @topic.posts.build(params[:post]) 

    # This is unnecessary as you're already adding 
    # the post to the topic with the build statement. 
    # @post.topic = @topic 

    if @post.save 
     flash[:success] = "Konu oluşturuldu!" 
     redirect_to :back 
    else 
     render 'static_pages/home' 
    end 
    end 

該控制器操作假設你要使用PUT請求到發佈嵌套在主題中的資源,因此您必須清理路由。

您有路線posts#create嵌套和unnested。 如果帖子總是應該被嵌套一個主題,你的控制器邏輯陳述中,就應該添加這個到嵌套的崗位資源:

resources :posts, except: [:new, :create] 

,然後更改form_for標籤這樣的:

<%= form_for [@topic, @post] do |f| %> 

這會告訴表單生成器您使用的是嵌套資源,並且會爲http請求使用正確的url。

另外 - 它看起來像你使用加載所有主題使用Topic.find(params[:id])。這不起作用 - 你在帖子控制器中,這是一個帖子ID。你應該加載這樣的id參數的帖子:Post.find(params[:id]),然後像這樣的話題:topic = post.topic