Carrierwave Gem Not Working - ruby-on-rails

I really have no idea what to do now. Image is showing up as nil in database. There are no errors showing up.
Model
class Resource < ActiveRecord::Base
mount_uploader :image, ImageUploader
attr_accessible :title, :url, :description, :tag
validates :title, presence: true, uniqueness: true
validates :url, presence: true
validates :description, presence: true
validates :tag, presence: true
belongs_to :user
acts_as_votable
validates_processing_of :image
validate :image_size_validation
private
def image_size_validation
errors[:image] << "should be less than 500KB" if image.size > 0.5.megabytes
end
end
Image Uploader
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_fill => [100, 100]
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
Form Partial
<%= form_for #resource, html: { multipart: true } do |f| %>
<% if #resource.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#resource.errors.count, "error") %> prohibited this pet
from being saved:</h2>
<ul>
<% #resouce.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :url %><br>
<%= f.text_area :url%>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :tag %><br>
<%= f.text_area :tag %>
<div class="field">
<%= f.label :image %><br>
<%= f.file_field :image %>
<% if f.object.image? %>
<%= image_tag f.object.image.thumb.url %>
<%= f.label :remove_image %>
<%= f.check_box :remove_image %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
Image tag in show
<%= image_tag #resource.image.thumb.url %>
Controller
class ResourcesController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
def index
#resources = Resource.page(params[:page]).per(15)
end
def show
#resource = Resource.where(:id => params[:id]).first
end
def edit
#resource = Resource.where(:id => params[:id]).first
end
def new
#resource = current_user.resources.build
end
def update
#resource = Resource.where(:id => params[:id]).first
respond_to do |format|
if #resource.update_attributes(resources_params)
format.html { redirect_to #resource, :notice => 'Resource was successfully
updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #resource.errors, :status =>
:unprocessable_entity }
end
end
end
def destroy
#toDelete = Resource.where(:id => params[:id]).first
puts #toDelete.id
if #toDelete.destroy
flash[:notice] = "Successfully deleted post!"
redirect_to root_path
else
flash[:alert] = "Error updating post!"
end
end
def create
#resource= current_user.resources.build(resources_params)
if #resource.save
redirect_to root_path
flash[:alert] = "Successfully created new resource!"
else
render "new"
end
end
def upvote
#resource = Resource.find(params[:id])
#resource.upvote_by current_user
redirect_to :back
end
def downvote
#resource = Resource.find(params[:id])
#resource.downvote_from current_user
redirect_to :back
end
private
def resources_params
params.require(:resource).permit(:title, :url, :description, :image, :tag)
end
end
If there is any other file you would like to see, I will post it.
Thank You.
EDIT
It was just a versioning problem......

Related

Rails Paperclip Gem Saving Multiple Attachments per Model instance

I'm very new to Rails development and having a problem saving multiple images/attachments to a model. My problem is that the code below is not actually saving to the item_images table when I submit the form. I am following This Article as a guide, though it seems to be a bit out of date. I feel I'm in a little over my head at this point so I hope someone can point out what I'm missing. Thanks!
I have the following models:
item.rb
class Item < ActiveRecord::Base
has_many :item_images, :dependent => :destroy
accepts_nested_attributes_for :item_images, :reject_if => lambda { |t| t['item_image'].nil? }
end
item_image.rb
class ItemImage < ActiveRecord::Base
belongs_to :item
has_attached_file :image,
:styles => { thumb: "100x100#", small: "400x400#", large: "700x700" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
My controller looks like this:
items_controller.rb
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
# GET /items
# GET /items.json
def index
#items = Item.all
end
# GET /items/1
# GET /items/1.json
def show
end
# GET /items/new
def new
#item = Item.new
4.times {#item.item_images.build}
end
# GET /items/1/edit
def edit
4.times {#item.item_images.build}
end
# POST /items
# POST /items.json
def create
#item = Item.new(item_params)
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: #item }
else
format.html { render :new }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /items/1
# PATCH/PUT /items/1.json
def update
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.json
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
#item = Item.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
params.require(:item).permit(:title, :description, :price, :available, :sort_shop, :sort_gallery, :item_type, :size)
end
end
form.html.erb
<%= form_for #item, html: { multipart: true } do |f| %>
<% if #item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#item.errors.count, "error") %> prohibited this item from being saved:</h2>
<ul>
<% #item.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :price %><br>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :available %><br>
<%= f.check_box :available %>
</div>
<div class="field">
<%= f.label :sort_shop %><br>
<%= f.number_field :sort_shop %>
</div>
<div class="field">
<%= f.label :sort_gallery %><br>
<%= f.number_field :sort_gallery %>
</div>
<div class="field">
<%= f.label :item_type %><br>
<%= f.text_field :item_type %>
</div>
<div class="field">
<%= f.label :size %><br>
<%= f.text_field :size %>
</div>
<%= f.fields_for :item_images do |builder| %>
<% if builder.object.new_record? %>
<div class="field">
<%= builder.label :image, "Image File" %>
<%= builder.file_field :image %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Try this in strong parameters in Items controller
params.require(:item).permit(:title, :description, :price, :available, :sort_shop, :sort_gallery, :item_type, :size,item_images_attributes: [:image ])
than in ItemImage.rb add this line
belongs_to :item, optional: true,
and remove this line from Item.rb
:reject_if => lambda { |t| t['item_image'].nil? }
`
If you get any error please reply

ROR number_field_tag give error 'not a number'

Error Message
I'm trying to insert a number value through 'number_field_tag' but keep getting the same error message. Does anyone know what is causing this?
new.html.erb
<% provide(:title, 'Products') %>
<h1>Products</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= render 'shared/error_messages_p' %>
<%= form_for([:admin, #product], :html => {multipart:true}) do |f| %>
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<%= f.label :description %>
<%= f.text_area :description, :rows => 6, class: 'form-control' %>
<%= f.file_field :image %>
<%= number_field_tag :stock_quantity, 1, min: 1, class: "form-control" %>
<%= f.label :price %>
<%= f.text_field :price, class: 'form-control' %>
<%= f.submit "Create product", class: "btn btn-primary" %>
<% end %>
</div>
</div>
products_controller.rb
class Admin::ProductsController < Admin::BaseController
before_action :set_product, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_product
def index
#products = Product.all
end
def show
#product = Product.find(params[:id])
end
def new
#product = Product.new
end
def edit
end
def create
#product = Product.new(product_params)
if #product.save
redirect_to [:admin, #product], notice: 'Product was successfully created.'
else
render :new
end
end
def update
if #product.update(product_params)
redirect_to #product, notice: 'Product was successfully updated.'
else
render :edit
end
end
def destroy
#product.destroy
redirect_to products_url, notice: 'Product was successfully destroyed.'
end
private
def set_product
#product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description, :image, :price, :stock_quantity)
end
def invalid_product
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to products_url, notice: 'Invalid product'
end
end
product model
class Product < ActiveRecord::Base
attr_accessor :image
validates :title, :description, :image, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :stock_quantity, numericality: { only_integer: true}
validates :image, allow_blank: true, format: {with: %r{\.(gif|jpg|png)\Z}i, message: 'must be a URL for GIF, JPG or PNG image.'}
mount_uploader :image, ImageUploader
solved the issue by replacing the quantity submit code with this:
<%= f.label :stock_quantity %>
<%= f.number_field :stock_quantity, min: 1, class: 'form-control' %>
can anyone enlighten me why 'number_field_tag' not working?
this solve it,
<%= number_field_tag 'product[stockquantity]', min: 1, class:"form-control" %>
thanks to previous commenters highlighting the html wordings.

Display a nested image with paperclip and rails

I have two models :
Post and Picture
class Post < ActiveRecord::Base
has_many :picture, :dependent => :destroy
accepts_nested_attributes_for :picture, :allow_destroy => true, :reject_if => lambda { |t| t['pictures'].nil? }
end
and
class Picture < ActiveRecord::Base
belongs_to :posts
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
Picture has a paperclip attachment : image
I created a nested form but i'm not able to know if my picture is saved correctly since i can't display in the show page.
Here is my form :
<%= form_for #post, html: { multipart: true} do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :brand %><br>
<%= f.text_field :brand %>
</div>
<div class="field">
<%= f.label :model %><br>
<%= f.text_field :model %>
</div>
<div class="field"><%= f.fields_for :picture do |p| %>
<%= p.file_field :image %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
My show page :
<p id="notice"><%= notice %></p>
<%= #post.picture.each do |pic| %>
<%= image_tag pic.image.url(:medium) %>
<% end %>
<p>
<strong>Title:</strong>
<%= #post.title %>
</p>
<p>
<strong>Description:</strong>
<%= #post.description %>
</p>
<p>
<strong>Brand:</strong>
<%= #post.brand %>
</p>
<p>
<strong>Model:</strong>
<%= #post.model %>
</p>
<%= link_to 'Edit', edit_post_path(#post) %> |
<%= link_to 'Back', posts_path %>
The post controller :
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
#posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
#post = Post.new
#post.picture.build
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
if params[:image]
params[:image].each { |image|
#post.picture.create(image: image)
}
end
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: #post }
else
format.html { render :edit }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :description, :brand, :model, picture_attributes: [ :id, :post_id, :image, :_destroy])
end
end
When i heat create post, i have no error the post is rendered but instead of having the image displayed i have this : "[]" ?
Terminal output :
Processing by PostsController#show as HTML
Parameters: {"id"=>"8"}
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 8]]
Picture Load (0.3ms) SELECT "pictures".* FROM "pictures" WHERE "pictures"."post_id" = ? [["post_id", 8]]
Is there something i did wrong ?
The first issue you have is that you've referenced your associations incorrectly:
#app/models/post.rb
class Post < ActiveRecord::Base
has_many :pictures #-> plural
end
#app/models/picture.rb
class Picture < ActiveRecord::Base
belongs_to :post #-> singular
has_attached_file :image
validates :image, content_type: { content_type: /\Aimage\/.*\Z/ }
end
You can see about the association names here:
A pro tip is to use the paperclip_defaults options in your application.rb:
#config/application.rb
...
config.paperclip_defaults: {
styles: { medium: "300x300>", thumb: "100x100>" },
default_url: "/images/:style/missing.png"
}
This will allow you to set the "defaults" for all implementations of Paperclip in your app, which can be overridden as you need in each model. Just makes it less messy I find...
In regards your error, you have all the pieces in place; I think the issue is your association names (see above).
This is what I would have:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
#post = Post.new
#post.pictures.build #-> plural
end
def create
#post = Post.new post_params
#post.save
end
private
def post_params
params.require(:post).permit(:title, :description, :brand, :model, picture_attributes: [:image, :_destroy])
end
end
You'd then be able to use the following form:
#app/views/posts/new.html.erb
<%= form_for #post, multipart: true do |f| %>
<%= f.fields_for :pictures do |p| %>
<%= p.file_field :image %>
<% end %>
<%= f.submit %>
<% end %>
--
This should submit to your db properly; to display the images, you can use the following:
#app/views/posts/show.html.erb
<% #post.pictures.each do |picture| %>
<%= image_tag picture.image.url %>
<% end %>

How to download multiple files of an id uploaded as a zip using carrierwave

i am using carrierwave for multiple file uploads.
My post model:
class Post < ActiveRecord::Base
has_many :post_attachments
accepts_nested_attributes_for :post_attachments
end
post_attachment.rb:
class PostAttachment < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
belongs_to :post
end
posts_controller.rb:
def show
#post_attachments = #post.post_attachments.all
end
def new
#post = Post.new
#post_attachment = #post.post_attachments.build
end
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
params[:post_attachments]['avatar'].each do |a|
#post_attachment = #post.post_attachments.create!(:avatar => a, :post_id => #post.id)
end
format.html { redirect_to #post, notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
private
def post_params
params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
end
and my posts/_form is:
<%= form_for(#post, :html => { :multipart => true }) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<%= f.fields_for :post_attachments do |p| %>
<div class="field">
<%= p.label :avatar %><br>
<%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Actually the above code is referred from Rails 4 multiple image or file upload using carrierwave.
Initially i have done single file upload using http://richonrails.com/articles/allowing-file-uploads-with-carrierwave where I used to download the file. For this I used to write a method in my controller as:
def download
respond_to do |format|
format.html {
if params[:post_id].nil?
redirect_to :back
else
begin
post = Post.find(params[:post_id])
attachment_file = File.join('public', post.attachment.url)
if File.exists?(attachment_file)
send_file attachment_file, :disposition => 'attachment'
else
redirect_to :back
end
rescue Exception => error
redirect_to :back
end
end
}
end
end
and in posts/index.html.erb:
<% #posts.each do |post| %>
<tr>
<td align="center">
<%= link_to image_tag("download.png"), download_post_path(post.id) %>
</td>
</tr>
<% end %>
attachment_uploader.rb:
class AttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
How can I download multiple files for a post_id as a zip with my code?

Rails nested attributes are not saving

I am new to rails and am learning to complete an Inventory System database project for school.
Here is my Item model:
class Item < ActiveRecord::Base
self.primary_key ='item_id'
validates :item_id, :presence => true
has_one :vendor_item, :dependent => :destroy
has_one :vendor, :through => :vendor_item
accepts_nested_attributes_for :vendor_item
end
Here is my item controller:
class ItemsController < ApplicationController
def new
#item = Item.new
#all_vendors = Vendor.all
#item_vendor = #item.build_vendor_item
end
def create
#item = Item.new(item_params)
vendor = params[:vendors][:id]
#item_vendor = #item.build_vendor_item(:vendor_id => vendor)
#item_vendor.save
#raise params.inspect
if #item.save
redirect_to #item
else
render 'new'
end
end
def show
#item = Item.find(params[:id])
#item_vendor = #item.vendor_item
end
def index
#items = Item.all
end
def priceUnder500
#priceUnder500 = Item.where("price < ?", 500)
respond_to do |format|
format.html
format.js
end
end
def priceOver500
#priceOver500 = Item.where("price > ?", 500)
respond_to do |format|
format.html
format.js
end
end
def edit
#item = Item.find(params[:id])
#all_vendors = Vendor.all
#vendor_item = #item.vendor_item
end
def update
#item = Item.find(params[:id])
vendor = params[:vendors][:id]
if #item.vendor_item.blank?
#item.build_vendor_item(:vendor_id => vendor)
end
if #item.update(params[:item].permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id]))
redirect_to items_path
else
render 'edit'
end
end
def destroy
#item = Item.find(params[:id])
#item.destroy
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id])
end
end
And my _form partial for items:
<%= form_for #item do |f| %>
<% if #item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#item.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% #item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :item_id, 'Item Id' %><br>
<%= f.text_field :item_id %>
</p>
<%= fields_for #item_vendor do |vii| %>
<div class= "vendorItemId">
<%= vii.label :vendor_item_id%>
<%= vii.text_field :vendor_item_id%><br>
</div>
<% end %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :category %><br>
<%= f.text_field :category %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :reorder_level %><br>
<%= f.text_field :reorder_level %>
</p>
<p>
<%= f.label :quantity %><br>
<%= f.text_field :quantity %>
</p>
<p>
<%= f.label :price %><br>
<%= f.text_field :price %>
</p>
<h3>Vendors:</h3>
<%= fields_for(#item_vendor) do |ab| %>
<div class= "field">
<%= ab.label "All Vendors:" %><br>
<%= collection_select(:vendors, :id, #all_vendors, :id, :name, {},{:multiple => false})%>
</div>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
vendor_item contains a reference to item_id, vendor_id, and has another attribute of vendor_item_id. When the program saves, item_id and vendor_id save but vendor_item_id does not save. I have tried every online source but cannot seem to get that one attribute to save. I am using rails 4. Thanks in advance for any help provided.
You haven't saving the result in an instance variable in create action.
Try giving like this in your create action.
def create
#item = Item.new(item_params)
vendor = params[:vendors][:id]
#item_vendor = #item.build_vendor_item(:vendor_id => vendor)
if #item.save
redirect_to #item
else
render 'new'
end
end
def create
#item = Item.new(item_params)
#vendor = params["item"]["vendors"]
if #item.save
#item.create_vendor_item(#vendor.id => vendor).save
redirect_to #item
else
render 'new'
end
end

Resources