我跟隨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
我得到這個錯誤:
undefined method `new_record?' for nil:NilClass
缺少什麼我在這裏?
重啓我的服務器後出現此錯誤:http://i.imgur.com/tLLE6jn.png –
可以嘗試使用'photo'而不是'f'' <%= link_to_add_association「添加照片」,照片,: user_photos%>' –
另一個錯誤:http://i.imgur.com/2LO5CqN.png –