Chrizzly
Chrizzly

Reputation: 43

Use profile pictures in Ruby on Rails

I'm trying to create a Library System with Rails 4. The books should have a title, author etc. and that already works fine but I also want each book to have a 'profile picture'. I don't really know how to upload and save the picture. The only thing I used so far was gravatar but that doesn't work for me this time.

That's my new.html

<h1>Add a new Book</h1>  
<div class="col-md-6 col-md-offset-3">
    <%= form_for(@book) do |f| %>
    <br>
      <%= f.label :title %>
      <%= f.text_field :title %><br><br>

      <%= f.label :author %>
      <%= f.text_field :author %><br><br>

      <%= f.label :isbn %>
      <%= f.text_field :isbn %><br><br>

      <%= f.label :description %>
      <%= f.text_field :description %><br><br>

      <%= f.label :Image %><br/>
      <%= f.file_field 'file' %>
      <%= f.submit "Upload" %><br><br>

  <%= f.submit "Add book", class: "btn btn-primary" %>
    <% end %>
</div>

The books_controller

class BooksController < ApplicationController

  def booklist
    @books = Book.all
    if params[:search]
      @books = Book.search(params[:search]).order("created_at DESC")
    else
      @books = Book.order("created_at DESC")
    end
  end

  def new
    @book = Book.new
  end

  def create
    @book = Book.new book_params
    if @book.save
      redirect_to booklist_path
    end
  end

   private
    def book_params
      params.require(:book).permit(:title, :author, :isbn,
        :description)
    end
end

And the booklist.html where I want to print it out

<div class="center hero-unit">
  <h1>Book Overview</h1>
  <% @books.each do |u| %>
  <tr>
      <td>
        <%= u.title %> | <%= u.author%> |    
        <hr>
        <br>
      </td>
  </tr>
  <% end %>

  <% @books.each do |b| %>
  <div>
    <h1><%= link_to b.title, b %></h1>
    <p><%= b.author %></p>
  </div>
<% end %>
</div>

The code snippet for the upload is my first try and it looks ok but I don't know if this is correct or how to continue with the create method :/ I hope you can help me and thanks in advance :)

Chrizzly

Upvotes: 2

Views: 3059

Answers (2)

Harish Ramachandran
Harish Ramachandran

Reputation: 293

The Carrierwave and Imagemagick gems work well. Look through Michael Hartl's Ruby on Rails tutorial for the step-by-step explanation (https://www.railstutorial.org/book/user_microposts#sec-micropost_images). Modify accordingly.

Upvotes: 2

errata
errata

Reputation: 26972

The most common solutions are the Carrierwave gem, the Paperclip Gem or something like filepicker.io which may make your life a bit easier.

Upvotes: 1

Related Questions