我最近决定测试Nested Form。从安装宝石到修改各自的模型都很顺利......然后当我尝试实际的东西时,我的运气就用光了。
模型
与所有其他友情模式一样,User
自我引用为:friend
。
class Share < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User"
end
这是我的Paperclip模型:
class Upload < ActiveRecord::Base
belongs_to :user
has_attached_file :document
FILE_FORMAT = ["Audio", "Document", "Image", "Video"]
end
这是通过Devise生成的:
class User < ActiveRecord::Base
attr_accessor :login
has_attached_file :image, :styles => { :medium => "120x120!" }
has_many :uploads
has_many :shares
has_many :friends, :through => :shares
has_many :inverse_shares, :class_name => "Share", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_shares, :source => :user
accepts_nested_attributes_for :uploads
end
表单
这是我的非嵌套表单,它可以正常工作:
<%= simple_form_for(upload, defaults: { wrapper_html: { class: 'form-group' }, input_html: { class: 'form-control' } }, html: { multipart: true }) do |f| %>
<%= f.input :file_name, label: "File Name:", input_html: {size: 19} %>
<br /><br />
<%= f.input :file_type, as: :select, collection: Upload::FILE_FORMAT, label: "File Type:" %>
<br /><br />
<%= f.input :document, as: :file, label: "File Path:" %>
<br /><br />
<%= f.submit "Upload File" %>
<% end %>
这是我想要解决的形式:
<%= simple_nested_form_for @user, url: uploads_path(@user), html: { method: :post } do |f| %>
<%= f.fields_for :uploads do |ff| %>
<%= ff.input :file_name, label: "File Name:", input_html: {size: 19} %>
<br /><br />
<%= ff.input :file_type, as: :select, collection: Upload::FILE_FORMAT, label: "File Type:" %>
<br />
<%= ff.input :document, as: :file, label: "File Path:" %>
<br /><br />
<%= ff.submit "Upload File" %>
<br /><br />
<%= ff.link_to_remove "Remove Document" %>
<% end %>
<%= f.link_to_add "Add Document", :uploads %>
<% end %>
遇到的错误
一个。使用@upload
(控制器中为@upload = Upload.new
)会得到ArgumentError in Uploads#new
。
<%= simple_nested_form_for @upload, url: uploads_path(@upload), html: { method: :post } do |f| %>
Invalid association. Make sure that accepts_nested_attributes_for is used for :uploads association.
B中。我试图修复的表单(请参阅表单部分,@user = current_user
)似乎表现为编辑请求。 /uploads/new
使用所有用户:uploads
的相应值加载所有表单,而不是允许填写表单。
℃。通过同一表单提交会出现param not found: upload
错误。
ActionController::ParameterMissing in UploadsController#create
问题
如何纠正嵌套表格以使其能够以正常形式运作?
谢谢。