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

相關問題