如何在照片上传后显示复选框?

时间:2013-03-12 14:52:35

标签: ruby ruby-on-rails-3 carrierwave

对于那些熟悉rubygems的人,我使用CarrierWave来允许我的应用上传照片。

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

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

如果选择要上传的照片,我怎样才能在我的视图中显示一个复选框以及上面的一些文字?

这是完整的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 %>

这是职位模型(相关部分)

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

3 个答案:

答案 0 :(得分:0)

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

if image.image_url  
 #your checkbox stuff and text stuff
end

答案 1 :(得分: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

答案 2 :(得分:0)

您好,您可以查看此链接以获取答案:它为您的照片上传者提供了一个Jquery功能。 http://blueimp.github.com/jQuery-File-Upload/

对于照片上传器gem,您可以使用:

https://github.com/thoughtbot/paperclip - Paperclip Gem http://railscasts.com/episodes/134-paperclip - Paperclip视频教程。 http://railscasts.com/episodes/253-carrierwave-file-uploads - CarrierWave视频教程。