Rails: CarrierWave file uploads

CarrierWave bootstrapCarrierWave file uploads

Installing CarrierWavein your Gemfile

gem 'carrierwave'

CarrierWave provides a generator called uploader to do this to which we pass the name we want to give our uploader, in this case image.

rails g uploader image

edit your show.html.erb which become

Next we’ll need to add the uploader to the Painting model.

rails g scaffold Painting name:string image:string

Next we’ll add the uploader to the Painting model which is done by calling the mount_uploader method

class Painting < ActiveRecord::Base
    
  attr_accessible :name, :image
  mount_uploader :image, ImageUploader
end

and then in your app/views/paintings/_form.html.erb edit your code, which become

  <div class="control-group">
    <%= f.label :image, :class => 'control-label' %>
    <div class="controls">
        <%= f.file_field :image, :class => 'text_field' %>
   </div>
  </div>

edit your show.html.erb which become

<dd><%= image_tag @painting.image_url.to_s %></dd>

Uploading Image via URL
adding line in _form.html.erb

<div class="control-group">
  <%= f.label :image, "or image URL", :class => 'control-label' %>
    <div class="controls">
     <%= f.text_field :remote_image_url %>
    </div>
  </div>

As we’ve added a field to the painting form we’ll need to add it to the list of attr_accessible fields in the Painting model

class Painting < ActiveRecord::Base
  attr_accessible :name, :image,  :remote_image_url
 
  mount_uploader :image, ImageUploader
end

Rails : Associating has_many relationships

bootstrap has_many associationproduct category model has_many association

we’ll start with a new App and we’ll generate a scaffold product model and category model, following this bellow:

rails g scaffold Product name:string price:decimal
rails g scaffold Category name:string
rails g migration add_category_id_to_products category_id:integer

don’t forget

rake db:migrate

in category model

class Category < ActiveRecord::Base
  has_many :product
  attr_accessible :name
end

next in Product Model

class Product < ActiveRecord::Base
  belongs_to :category
  attr_accessible :name, :price, :category_id
end

finally, edit your code in app/views/product model, in index.html.erb and show.html.erb

<%= @product.category_id %>

which become

<%= @product.category.name %>

and specially
_form.html.erb

<div class="control-group">
      <%= f.label :category_id, :class => 'control-label' %>
      <div class="controls">
        <%= f.collection_select :category_id, Category.all, :id, :name %>
     
      </div>
    </div>