如何将file_field_tag与carrierwave一起使用

时间:2015-01-26 08:02:06

标签: html ruby-on-rails-4 file-upload carrierwave form-for

我试图用帮助器优化我的项目并遇到问题。 优化之前我的.erb看起来像:

# app/views/object/_form.html.erb
<%= form_for(@object) do |f| %>
<%= f.label :image %>
<%= f.file_field :image %>
<%= f.submit %>
<% end %>

优化后,我希望看到:

# app/views/object/_form.html.erb
<%= form_for(@object) do |f| %>
<%= f.labeled_image :image %>
<%= f.submit %>
<% end %>

# app/helpers/application_helper.rb
module ApplicationHelper

class ActionView::Helpers::FormBuilder
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::FormOptionsHelper
include ActionView::Helpers::AssetTagHelper
include ActionView::Helpers::FormHelper

def labeled_image (name, options = {})
  label = label_tag @object_name + "[#{name}]", I18n.t(name)
  file_field = file_field_tag @object_name + "[#{name}]"
  content_tag 'div', label+file_field
end

end

end

此代码中没有错误。此外,它生成了正确的代码,但是carrierwave没有获取我发送的文件。

我发现只有这种解决方法:

# app/views/object/_form.html.erb
<%= form_for(@object) do |f| %>
<%= f.labeled_image f, :image %>
<%= f.submit %>
<% end %>

# app/helpers/application_helper.rb
module ApplicationHelper

class ActionView::Helpers::FormBuilder
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::FormOptionsHelper
include ActionView::Helpers::AssetTagHelper
include ActionView::Helpers::FormHelper

def labeled_image (f, name, options = {})
  label = label_tag @object_name + "[#{name}]", I18n.t(name)
  file_field = f.file_field name
  content_tag 'div', label+file_field
end

end

end

但它看起来像noob:)

1 个答案:

答案 0 :(得分:0)

简单

只需self.file_field name