jeudi 21 avril 2016

Image upload using carrierwave in show page

Using Rails 4 and Ruby 2.2,

I have book as model which should have image upload functionality in the show page of book. So User can create the book first and from show page upload the multiple images for book. I have used carrierwave as gem and have separate model created for Image.

image.rb

class Image < ActiveRecord::Base
  belongs_to :book

  mount_uploader :avatar, AvatarUploader
end

book.rb

class Book < ActiveRecord::Base
    belongs_to :subject, dependent: :destroy
    belongs_to :user, dependent: :destroy
    has_many :images, dependent: :destroy
end

books/show.html.erb

<%= form_for(Image.new, :html => { :multipart => true }) do |f| %>
   <div class="field">
     <%= f.label :name %><br>
     <%= f.text_field :name %>
     <%= hidden_field_tag "image[book_id]", @book.id %>
   </div>
   <%= f.fields_for :images do |p| %>
     <div class="field">
       <%= p.label :avatar %><br>
       <%= p.file_field :avatar, :multiple => true, name: "images[avatar]" %>
     </div>
   <%end%>

   <div class="actions">
     <%= f.submit %>
   </div>
<% end %>

schema.rb

  create_table "images", force: :cascade do |t|
    t.datetime "avatar_updated_at"
    t.datetime "created_at",                    null: false
    t.datetime "updated_at",                    null: false
    t.integer  "book_id",           limit: 4
    t.string   "avatar",            limit: 255
    t.string   "name",              limit: 255
  end

  create_table "books", force: :cascade do |t|
    t.string   "title",       limit: 255
    t.integer  "page_number", limit: 4
    t.text     "description", limit: 65535
    t.datetime "created_at",                                null: false
    t.datetime "updated_at",                                null: false
    t.integer  "user_id",     limit: 4
    t.integer  "subject_id",  limit: 4
    t.boolean  "active",                    default: false
  end

Now I am kind of unable to proceed with this, can someone guide me on this because I am having form in books/show page and I need to show the image on the same page after successful updation of images.(Multiple images can be uploaded)

Thanks in advance

let me know if I need to provide any more information.

Aucun commentaire:

Enregistrer un commentaire