【问题标题】:RAILS 4 First argument in form cannot contain nil or be emptyRAILS 4 表单中的第一个参数不能包含 nil 或为空
【发布时间】:2015-09-13 03:02:22
【问题描述】:

您好,我遇到了一个问题:“表单中的第一个参数不能包含 nil 或为空”。由于我是 Rails 新手,我很难使用现有的答案(仍然找不到我的错误)请看一下:

Showing /home/ubuntu/workspace/app/views/admin/categories/_form.html.haml where line #1 raised:

First argument in form cannot contain nil or be empty
Extracted source (around line #1):


= simple_form_for [:admin, @category], :html => {class: "form-horizontal"} do |f|
  .form-group
    = f.label :name, class: "col-sm-2 control-label"
    .col-sm-10
      = f.input_field :name, label: false, class: "form-control"
  - if @category.id.present?

渲染:

= render 'form', :url => admin_categories_path(@category)

控制器:

class Admin::CategoriesController < AdminController

before_action :set_category, :only =>[:show, :edit, :destroy, :update]

  def index
    @categories = Category.all
    respond_to do |format|
        format.html
        format.json {render json: @categories}
    end
  end

  def show
    respond_to do |format|
       format.html
       format.json { render json: @category }
    end    
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(category_params)

    respond_to do |format|
        if @category.save
            format.html {redirect_to admin_categories_path, notice: 'Category created'}
        else
            format.html {render action: 'new', alert: 'Error while creating'}
        end
    end    
  end

  def edit
  end

  def update

    respond_to do |format|
        if @category.update{post_params}
            format.html {redirect_to admin_post_path, notice: "Category updated"}
        else
            format.html {render action: 'edit', alert: "Error while editing"}
        end
    end  

  end

  def destroy
    @category.destroy
    respond_to do |format|
        format.html {redirect_to admin_categories_path, notice "#{Category.title} deleted"}
    end
  end

  protected

  def get_category
    @category = Category.find(params[:id])
  end

  def category_params
    params.require(:category).permit(:title, :body)
  end
end

【问题讨论】:

  • 当您查看新操作或编辑操作时会发生这种情况吗?
  • 它发生在我去路由时:/admin/categories/new 所以发布
  • 错误是First argument in form cannot contain nil or be empty Extracted source (around line #1): 所以要么@category 为nil,要么将:admin 传递给simple_form_for [:admin, @category] 被评估为nil

标签: ruby-on-rails ruby forms


【解决方案1】:

在您的before_action 中,确保您的数组中有:new。现在你没有,所以当你去 /admin/categories/new 时@category 没有被设置

【讨论】:

  • 它正在被设置,在 new 操作本身中。
  • 您的意思是在控制器中?如果是,它没有帮助
【解决方案2】:

好的,我明白了。 对它有一点新看法:

所以 - 它在管理目录中呈现类别控制器 - 这是空的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多