0

对于那些熟悉 ruby​​gems 的人,我使用 CarrierWave 允许在我的应用程序上上传照片。

这是我在视图中使用的代码

Add a photo:
  <%= f.file_field :image %>

How can I make a checkbox appear in my View along with some text above it only IF a photo is selected for upload?

这是完整的 post.html.erb 视图

<%= form_for @post, :html => {:multipart => true} do |f| %>
  <%= render 'shared/error_messages', object: @post %>
  <div class="field">
    <%= f.text_area :content, :cols => 5, :rows => 5 %>
  </div>
  Add a photo:<br>
  <%= f.file_field :image %>
  <br>
  <%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>

这是post模型(相关部分)

class Post < ActiveRecord::Base
  attr_accessible :content, :image
  belongs_to :user

  mount_uploader :image, ImageUploader
end

和上传者模型

class ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  def filename
     "#{secure_token(10)}.#{file.extension}" if original_filename.present?
   end

   def cache_dir
    "#{Rails.root}/tmp/uploads"
  end

protected
  def secure_token(length=16)
    var = :"@#{mounted_as}_secure_token"
    model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
  end


end
4

2 回答 2

0

因此,您可以使用检查图像是否被选中的条件,然后您可以将文本框与文本一起附加,如下所示:

if image.image_url  
 #your checkbox stuff and text stuff
end
于 2013-03-12T15:08:38.637 回答
0

每个帖子只存储一张照片,您需要将照片存储在另一个表中。

class Post < ActiveRecord::Base
 attr_accessible :content, :title
 has_many :images
end

class Image < ActiveRecord::Base
  attr_accessible :image, :image_cache, :post_id
  belongs_to :post
  mount_uploader :image, ImageUploader
end

因此,您可以选择要与每个帖子关联的图片。在这里找到一个例子:https ://github.com/kdironside/carrierwave-multi-file-upload

于 2013-03-12T18:21:01.523 回答