我正在关注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
我在这里缺少什么?
答案 0 :(得分:3)
我认为这只是一个简单的错字 - 您的fields_for :user_photos
应该是f.fields_for :user_photos
(以便它与父表单正确连接)。
答案 1 :(得分: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>