0

我正在开发一个项目,用户可以创建帖子,其他人可以发送有关该主题的帖子。我的资源文件是:

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>

为什么没有错误不显示?

4

2 回答 2

1

您在“创建”操作中缺少 @topics。是的,它被设置在你的“家”中,它呈现了表单,但是在提交时,它传递给“创建”,然后它必须再次加载变量,在你的情况下,它去的时候没有设置@topics渲染“static_pages/home”。你需要..

...
if @post.save
  flash[:success] = "Yorum oluşturuldu!"
  redirect_to topic_path(@topic)
else
  @topics = Topic.paginate :page => params[:page], :per_page => 20
  render 'static_pages/home'
end
于 2012-06-29T12:38:24.497 回答
0

你从不设置@topics,只有@topic@topics零也是如此。

如果出现错误,您会渲染static_pages/home,这需要这些。您应该重新渲染newor edit

于 2012-06-29T12:15:52.410 回答