2

我跟随this tutorial,作者正在使用Slim。由于我比较熟悉标准的Rails的形式,我尝试了纤薄的标记更改为正常的形式,像这样:标准导轨形式+ Cocoon gem:未定义的方法`new_record?'为零:NilClass错误

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内强PARAMS。我没有触摸控制器内部的其他方法,因为我使用的是rails g scaffold user name:string生成器。

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

enter image description here

我得到这个错误:

undefined method `new_record?' for nil:NilClass 

缺少什么我在这里?

回答

0

请试试这个。

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> 
+0

重启我的服务器后出现此错误:http://i.imgur.com/tLLE6jn.png –

+0

可以尝试使用'photo'而不是'f'' <%= link_to_add_association“添加照片”,照片,: user_photos%>' –

+0

另一个错误:http://i.imgur.com/2LO5CqN.png –

3

我相信这只是一个简单的拼写错误来解决这个问题 - 你fields_for :user_photos应该f.fields_for :user_photos(以便正确连接到父窗体)。

+0

在'fields_for'前面加上'f'后,我只获取用户名字段,嵌套字段不见了。 http://i.imgur.com/DapYxag.png –

+0

这是正常的,因为在创建时没有嵌套项目,除非你在控制器中创建一个项目,比如'@ user.user_photos.build' – nathanvda

相关问题