我想做一个应用程序,用户可以创建一个主题,然后其他人可以发帖。我将资源嵌套在我的 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 %>