0

我想做一个应用程序,用户可以创建一个主题,然后其他人可以发帖。我将资源嵌套在我的 routes.rb 中:

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 并发送 Posts 和 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 %>
4

1 回答 1

1

有一些事情应该为您解决问题。

首先,您在帖子控制器中的创建操作有点错误 - 它应该看起来像这样:

  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嵌套和未嵌套的路由。如果帖子总是应该嵌套在您的控制器逻辑所说明的主题中,那么您应该将其添加到未嵌套的帖子资源中:

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

然后将该form_for标签更改为:

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

这告诉表单生成器您正在使用嵌套资源,并将使用正确的 url 进行 http 请求。

另外 - 看起来你正在使用加载所有主题Topic.find(params[:id])。这是行不通的——你在帖子控制器中,这是一个帖子ID。您应该像这样加载带有 id 参数的帖子:Post.find(params[:id])然后是这样的主题:topic = post.topic

于 2012-06-26T21:37:31.327 回答