【问题标题】:Standard Rails form + Cocoon gem: undefined method `new_record?' for nil:NilClass error标准 Rails 表单 + Cocoon gem:未定义方法 `new_record?'对于 nil:NilClass 错误
【发布时间】:2016-03-01 03:47:40
【问题描述】:

我正在关注this tutorial,作者正在使用 Slim。由于我更熟悉标准 Rails 表单,因此我尝试将 slim 标记更改为普通表单,如下所示:

new.html.erb

<%= render 'form' %>

_form.html.erb

<%= form_for(@user) do |f| %>
  <%= f.text_field :name %>

  <br><br>

  <%= fields_for :user_photos do |photo| %>
    <%= render "user_photo_fields", f: photo %>
    <span class="links">
      <%= link_to_add_association "add photo", f, :user_photos %>
    </span>
  <% end %>

  <%= f.submit %>
<% end %>

_user_photo_fields.html.erb

<div class="nested-fields">
    <div class="field">
        <%= f.file_field :photo %>
    </div>
    <%= link_to_remove_association "remove", f %>
</div>

还有,这是我的模型:

class User < ActiveRecord::Base
    has_many :user_photos
    validates_presence_of :name
    accepts_nested_attributes_for :user_photos, allow_destroy: true
end

class UserPhoto < ActiveRecord::Base
    belongs_to :user
    mount_uploader :photo, PhotoUploader
end

最后,users_controller.rb 中的强大参数。因为我使用的是rails g scaffold user name:string生成器,所以我没有触及控制器内部的其余方法。

def user_params
      params.require(:user).permit(:name, user_photos_attributes: [:id, :photo, :_destroy])
    end

我收到此错误:

undefined method `new_record?' for nil:NilClass

我在这里错过了什么?

【问题讨论】:

    标签: forms ruby-on-rails-4 nested-forms nested-attributes cocoon-gem


    【解决方案1】:

    我认为这只是一个简单的错字 - 您的 fields_for :user_photos 应该是 f.fields_for :user_photos(以便正确连接到父表单)。

    【讨论】:

    • fields_for前面加上f后,只得到用户名字段,嵌套字段不见了。 i.imgur.com/DapYxag.png
    • 这很正常,因为在创建的那一刻没有嵌套项,除非你在控制器中创建一个,比如@user.user_photos.build
    【解决方案2】:

    请尝试一下。

    class User < ActiveRecord::Base
      has_many :user_photos
      validates_presence_of :name
      accepts_nested_attributes_for :user_photos, allow_destroy: true
    end
    

    你可以尝试通过删除 f 来解决这个问题

      <div class="nested-fields">
            <div class="field">
                <%= file_field :photo %>
            </div>
            <%= link_to_remove_association "remove" %>
      </div>
    

    【讨论】:

    • 可以尝试用photo代替f&lt;%= link_to_add_association "add photo", photo, :user_photos %&gt;
    • 请尝试以上更改。
    • 仍然得到undefined method 'attr_accessible' for 指向这一行的错误attr_accessible :name, user_photos_attributes: [:id, :photo, :_destroy]
    • 如果你使用 rails 4.1 那么你必须删除attr_accessible。您可以使用github.com/rails/strong_parameters
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多