我正在开发一个项目,用户可以创建帖子,其他人可以发送有关该主题的帖子。我的资源文件是:
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :topics , only: [ :show, :create, :destroy] do
resources :posts, only: [:create, :new]
我的topics_form.html.erb:
<%= form_for(@topic) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :title, placeholder: "yeni başlık girin..." %>
</div>
<%= f.submit "Gönder", class: "btn btn-large btn-primary" %>
<% end %>
我的创建动作是:
def create
@topic = current_user.topics.build(params[:topic])
if @topic.save
flash[:success] = "Konu oluşturuldu!"
redirect_to root_path
else
render 'static_pages/home'
end
end
我的 posts_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_controller 创建操作是:
def create
@topic= Topic.find(params[:topic_id])
@post = @topic.posts.build(params[:post])
@post.user = current_user
@post.topic_id = @topic.id
if @post.save
flash[:success] = "Yorum oluşturuldu!"
redirect_to topic_path(@topic)
else
render 'static_pages/home'
end
end
这是我的 error_messages.html.erb:
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
如果我测试空帖子和空主题。我收到此错误:
undefined method `each' for nil:NilClass
Extracted source (around line #2):
1:
2: <% @topics.each do |topic|%>
3: <li><%=link_to topic.title, topic_path(topic) %></li>
4:
5: <%= will_paginate @topics %>
我的 static_pages_controller.rb :
def home
if signed_in?
@topic = current_user.topics.build if signed_in?
end
@topics = Topic.paginate :page => params[:page], :per_page => 20
end
和我的 home.html.erb:
<% if signed_in? %>
<div class="row">
<%= render 'shared/user_info' %>
<%= render 'shared/topic_form' %>
<ol class="topics-signedin">
<%= render 'shared/topics' %>
</ol>
为什么没有错误不显示?