ユーザーがトピックを作成し、他のユーザーがその後投稿できるアプリケーションを作成したいと考えています。私は自分のリソースを自分の 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 と送信済みの投稿と 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 %>