ユーザーがトピックを開き、他のユーザーが投稿にコメントできるアプリケーションを完成させようとしています。私は自分のリソースを 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 にあります =>
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for([@topic, @post]) do |f| %>