避免使用 fields_for 将单个记录添加到关联模型

发布于 2025-01-03 17:57:34 字数 872 浏览 0 评论 0原文

我有以下关联:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝在阴天搁浅。 2025-01-10 17:57:34
<%= form.fields_for :large_photos, @developer.large_photos.build do |project_fields| %>

此行不是为每张现有照片创建字段,而是构建一个新的 Photo 并仅显示该照片的字段(因此字段为空,我认为这就是您想要的)。

<%= form.fields_for :large_photos, @developer.large_photos.build do |project_fields| %>

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文