避免使用 fields_for 将单个记录添加到关联模型
我有以下关联:
class Developer < ActiveRecord::Base
has_many :large_photos, :class_name => 'Photo', :conditions => { :large => true }, :reject_if => proc { |x| x['image'].blank? }
end
class Photo < ActiveRecord::Base
belongs_to :developer
mount_uploader :image, ImageUploader # Carrierwave
end
现在,我正在构建一个开发表单,提交后,将添加一个文件字段来上传新的照片
。目前我有:
<%= form_for @developer do |form| %>
<%= form.fields_for :large_photos do |sf| %>
<div class="dropzone">
<%= sf.file_field :image %>
<%= sf.hidden_field :large, :value => '1' %>
<%= sf.hidden_field :image_cache %>
</div>
<% end %>
<% end%>
现在,我遇到的问题是 fields_for
正在循环遍历现有记录(当然是这样!),我希望避免这种情况,我只想添加用于上传新照片的单个文件字段。我该怎么办呢?
I have the following associations:
class Developer < ActiveRecord::Base
has_many :large_photos, :class_name => 'Photo', :conditions => { :large => true }, :reject_if => proc { |x| x['image'].blank? }
end
class Photo < ActiveRecord::Base
belongs_to :developer
mount_uploader :image, ImageUploader # Carrierwave
end
Now, I'm looking to build a Development form which, when submitted, will add a single file field for uploading a new Photo
. At the moment I have:
<%= form_for @developer do |form| %>
<%= form.fields_for :large_photos do |sf| %>
<div class="dropzone">
<%= sf.file_field :image %>
<%= sf.hidden_field :large, :value => '1' %>
<%= sf.hidden_field :image_cache %>
</div>
<% end %>
<% end%>
Now, the problem I have with this is that fields_for
is looping through the existing records (of course it is!) which I'd prefer to avoid, I just want to add a single file field for uploading a new photo. How would I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行不是为每张现有照片创建字段,而是构建一个新的
Photo
并仅显示该照片的字段(因此字段为空,我认为这就是您想要的)。Instead of creating the fields for each existing photos, this line builds a new
Photo
and show the fields only for this one (so the fields are empty, I think it's what you want).