我最近决定测试Nested Form。从安装 gem 到修改各自的模型,一切都很顺利......然后当我尝试实际的东西时,我的运气就用完了。
楷模
像所有其他友谊模型一样,User
自引用为:friend
.
class Share < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User"
end
这是我的回形针模型:
class Upload < ActiveRecord::Base
belongs_to :user
has_attached_file :document
FILE_FORMAT = ["Audio", "Document", "Image", "Video"]
end
这个是通过设计生成的:
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 %>
遇到的错误
A. 使用@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
使用 all user 的相应值加载所有表单,:uploads
而不是允许填写表单。
C. 通过相同的表格提交会param not found: upload
出错。
ActionController::ParameterMissing in UploadsController#create
问题
嵌套形式应该如何纠正,以使其能够像正常形式一样发挥作用?
谢谢你。