【问题标题】:Rails error 'First argument in form cannot contain nil or be empty'Rails 错误“表单中的第一个参数不能包含 nil 或为空”
【发布时间】:2015-08-24 06:00:05
【问题描述】:

我已经尝试了所有关于如何摆脱错误的 Stack 帖子 表单中的第一个参数不能包含 nil 或为空',并且他们的解决方案都不适合我。

我的应用涉及发布帖子,用户可以在其中上传图片。我希望他们能够直接从他们的文件系统上传,而不是获取图片网址。

这是我的控制器:

  class PostsController < ApplicationController
      before_action :all_posts, only: [:feed, :create]
      respond_to :html, :js

    def show
      @post = Post.find_by_id(params['id'])
    end


    def create
      @post = Post.create(post_params)
    end

    def new
      @post = Post.new
    end

    private

    def all_posts
      @posts = Post.all
    end

    def post_params
      params.require(:post).permit(:caption, :content, :image)
    end

  end

还有new.html.erb:

<footer>
  <%= form_for @post, :html => {:multipart => true} do |f| %>
    <%= f.text_field :caption %>
    <%= f.text_field :content %>
    <%= f.file_field :image %>
    <%= f.submit %>
  <% end %>
</footer>

人们一直建议将@post = Post.new 添加到表单和操作中,但没有一个对我有用。

另外,我已经检查了我的数据库,目前有 7 个帖子。

非常感谢您的帮助。

【问题讨论】:

  • 你对应的控制器动作是什么?你的观点是:feed.html.erb你应该在你的posts_controller中有一个feed动作

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

您收到此错误是因为当您调用 form_for(@post,.... 时,您的 @postnil

您必须在控制器的相应操作中实例化@post 实例变量。由于您现在没有它,因此您会收到此错误。

通过查看您的其余代码,我认为您希望将帖子上传到您的new.html.erb 文件中,而不是您在问题中提到的feed.html.erb

【讨论】:

  • 好的,谢谢。现在我收到错误消息:“#:0x007fcd2bec23e0> 的未定义方法 `posts_path'”。你知道为什么会这样吗?
  • 你在哪里得到这个错误?你能分享完整的错误堆栈跟踪吗?
  • 我将操作更改为 feed,现在:NoMethodError in Posts#feed undefined method `posts_path' for #:0x007fcd2bec23e0> 它突出显示: {:multipart => true} 做 |f| %>
  • 您可以尝试将视图更改为new.html.erb 并保持操作为new
  • 我将视图更改为 new.html.erb,并用它调整了所有内容,但仍然出现相同的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多