形式中的第一个参数不能包含nil或者使用Gamepost为空

时间:2014-04-11 02:43:23

标签: ruby-on-rails

在Rails 4的游戏页面中收到此错误  ActionView :: Template :: Error(表单中的第一个参数不能包含nil或为空):

_Gamepost_form.html.erb

<%= form_for (@gamepost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new game sale..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

控制器

class GamepostsController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy, :]
  before_action :correct_user,   only: :destroy


  def index
    @gamepost = current_user.gameposts.build
  end

  def create
    @gamepost = current_user.gameposts.build(gamepost_params)
    if @gamepost.save
      flash[:success] = "Game Sale created!"
      redirect_to root_url
    else
      @gamefeed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @gamepost.destroy
    redirect_to root_url
  end

  private

    def gamepost_params
      params.require(:gamepost).permit(:content)
    end

    def correct_user
      @gamepost = current_user.gameposts.find_by(id: params[:id])
    rescue
      redirect_to root_url
    end
end

使用微博有一个类似的例子,它的工作正常,不知道为什么这个实例不起作用 在回答Vee提供后,

ActionView::Template::Error (undefined method `any?' for nil:NilClass):
1: <% if @gamefeed_items.any? %>
2:   <ol class="gameposts">
3:     <%= render partial: 'shared/gamefeed_item', collection: @gamefeed_items %> 

显示在同一页面

1 个答案:

答案 0 :(得分:0)

跟进你的问题中的评论。

您似乎正在通过index操作呈现该表单。

class GamepostsController < ApplicationController
  before_action :signed_in_user, only: [ :index, :create, :destroy]
  ...

  def index
    @gamepost = current_user.gameposts.build
  end

  ...
end

请注意,您还需要在:index中添加:new而不是before_action :signed_in_user。这是为了确保current_user可用,以便current_user.gameposts.build不会失败!