I'm running Rails 4 on Windows, and trying to automate a population script. My populatepins.rake file is:
namespace :db do
desc "Fill database with sample data"
task populatepins: :environment do
User.all.each do |user|
puts "[DEBUG] uploading images for user #{user.id} of #{User.last.id}"
2.times do |n|
image = File.open(Dir.glob(File.join(Rails.root, 'testpics', '*')).sample) # sample picks one random
puts "[DEBUG] searching for FILE: #{File.absolute_path(image)}"
description = %w(cool awesome crazy wow adorable incredible).sample # %W converts to an array
puts "[DEBUG] past description: #{description}"
user.pins.create!(image: image, description: description)
puts "[DEBUG] endofloop"
end
end
end
end
However, when running the script I get loops with this error:
C:\Sites\code\testrails>rake db:populatepins
[DEBUG] uploading images for user 45 of 47
[DEBUG] searching for FILE: C:/Sites/code/testrails/testpics/_MG_5557.jpg
[DEBUG] past description: adorable
C:/RailsInstaller/Ruby1.9.3/bin/rake: No such file or directory - lsof -p 13752
C:/RailsInstaller/Ruby1.9.3/bin/rake: No such file or directory - lsof -p 13752
C:/RailsInstaller/Ruby1.9.3/bin/rake: No such file or directory - lsof -p 13752
C:/RailsInstaller/Ruby1.9.3/bin/rake: No such file or directory - lsof -p 13752
[DEBUG] endofloop
I thought it might be the '\' vs '/' path problem as per https://www.ruby-forum.com/topic/194682, but couldn't really figure out a solution that worked...
Any help will be much appreciated, thanks!
EDIT: here is what the model looks like (JLX is me commenting...)
class Pin < ActiveRecord::Base
has_attached_file :image, styles: { large: "640x480>", medium: "320x240>", thumb: "200x200#"} # Paperclip association
validates :description, presence: true #, length: { minimum: 10 }
validates :user_id, presence: true
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']},
size: {less_than: 5.megabytes}
# JLX link to users
belongs_to :user # can only have one user associated
# We are modifying the default getter/setter method created automatically when generating the image_url var
def image_remote_url=(url_value)
self.image = URI.parse(url_value) unless url_value.blank?
super # inherits the default method behaviour
end
end
And this is what the controller looks like:
class PinsController < ApplicationController
# JLX Devise method
before_action :authenticate_user!, except: [:index, :show]
before_action :set_pin_global, only: [:show]
before_action :set_pin_user, only: [:edit, :update, :destroy]
# GET /pins
# GET /pins.json
def index
##pins = Pin.all
#pins = Pin.order("created_at desc")
end
# GET /pins/1
# GET /pins/1.json
def show
end
# GET /pins/new
def new
##pin = Pin.new
#pin = current_user.pins.new
end
# GET /pins/1/edit
def edit
end
# POST /pins
# POST /pins.json
def create
##pin = Pin.new(pin_params)
#pin = current_user.pins.new(pin_params)
respond_to do |format|
if #pin.save
format.html { redirect_to #pin, notice: 'Pin was successfully created.' }
format.json { render action: 'show', status: :created, location: #pin }
else
format.html { render action: 'new' }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pins/1
# PATCH/PUT /pins/1.json
def update
respond_to do |format|
if #pin.update(pin_params)
format.html { redirect_to #pin, notice: 'Pin was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
#pin.destroy
respond_to do |format|
format.html { redirect_to pins_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin_global
#pin = Pin.find(params[:id])
end
def set_pin_user
#pin = current_user.pins.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description, :image, :image_remote_url) # JLX added :image
end
end
Related
I am trying to integrate Twilio and my rails application to send different text messages based on what option is chosen and saved to the database in the form. However after studying the docs and viewing the example applications they provide (Send ETA Notifications), saving the completed form, no text message is sent and I cannot figure out why. I would love some suggestions
job_status are the options to choose from which the text message body needs to change with:
JOB_STATUSES = ["Wildey Que", "In Service-Bay", "Awaiting Approval",
"Awaiting Parts", "Jackson Collection Que", "Wildey Collection Que",
"Completed"]
message_sender.rb
class MessageSender
require 'twilio-ruby'
def self.send_message(job_id, host, to, message)
new.send_message(job_id, host, to, message)
end
def initialize
# To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit
# https://www.twilio.com/console
account_sid = ENV['---'] (These are entered)
auth_token = ENV['---']
#client = Twilio::REST::Client.new(account_sid, auth_token)
end
def send_message(job_id, host, to, message)
#client.messages.create(
from: twilio_number,
to: to,
body: message,
status_callback: "http://#{host}/jobs/#{job_id}"
)
end
private
def twilio_number
# A Twilio number you control - choose one from:
# https://www.twilio.com/console/phone-numbers/incoming
# Specify in E.164 format, e.g. "+16519998877"
ENV['+17652957305']
end
end
jobs_controller.rb
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /jobs
# GET /jobs.json
def index
if(params.has_key? (:job_status))
#jobs = Job.where(job_status: params[:job_status]).order("created_at desc")
else
#jobs = Job.all.order("created_at desc")
end
end
# GET /jobs/1
# GET /jobs/1.json
def show
end
# GET /jobs/new
def new
#job = current_user.jobs.build
end
# GET /jobs/1/edit
def edit
end
#TWILLIO INITILIZATION
def send_initial_notification
#job.job_status = :Wildey_Que
if #job.save
message = 'Equip4you: Thanks for dropping your machine off, we will keep you updated here every step of the way'
notify(message)
else
redirect_with_error
end
end
def send_delivery_notification
#job.job_status = :Completed
if #job.save
message = 'Equip4you: Thank you for allowing us to take care of your machine for you, if you have any further questions or concerns feel free to contact 425-9999'
notify(message)
else
redirect_with_error
end
end
#END TWILLIO INIT
# POST /jobs
# POST /jobs.json
def create
#job = current_user.jobs.build(job_params)
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Job was successfully created.' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
#job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, notice: 'Job was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# TWILLIO INNIT
def notify(message)
MessageSender.send_message(
#job.id, request.host, #job.cell_number, message)
redirect_to jobs_url, notice: 'Message was delivered'
end
def redirect_with_error
message = "An error has occurred updating the ticket status"
redirect_to orders_url, flash: { error: message }
end
#TWILLIO INIT END
# Use callbacks to share common setup or constraints between actions.
def set_job
#job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:job_status, :purchase_name, :contact_name, :cell_number, :home_number, :other_number, :other_number, :address, :machine_mod, :item_number, :serial_number, :concern, :accessories, :pickup_location, :paid, :invoice_number, :outcome, :avatar)
end
end
Routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
resources :jobs
devise_for :users
root to: 'jobs#index'
post '/jobs/new', to: 'jobs#new', as: 'initial_notifications'
post '/jobs/new', to: 'jobs#new', as: 'delivery_notifications'
routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
resources :jobs
devise_for :users
root to: 'jobs#index'
post '/jobs/new', to: 'jobs#new', as: 'initial_notifications'
post '/jobs/new', to: 'jobs#new', as: 'delivery_notifications'
Please check this def. It looks weird.
def twilio_number
# A Twilio number you control - choose one from:
# https://www.twilio.com/console/phone-numbers/incoming
# Specify in E.164 format, e.g. "+16519998877"
ENV['+17652957305']
end
I am using Rails scaffold to create a simple model called Movies that contains the movie's name, director, synopsis and poster.
I am using the Carrierwave gem to upload the poster image. When I first boot up the rails server, I get the following message:
NameError in MoviesController#new
uninitialized constant Movie::PosterUploader
The extracted source the error screen displays is my models/movie.rb file:
class Movie < ApplicationRecord
mount_uploader :poster, PosterUploader
end
Here is my movies controller:
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy]
# GET /movies
# GET /movies.json
def index
#movies = Movie.all
end
# GET /movies/1
# GET /movies/1.json
def show
end
# GET /movies/new
def new
#movie = Movie.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
#movie = Movie.new(movie_params)
respond_to do |format|
if #movie.save
format.html { redirect_to #movie, notice: 'Movie was successfully
created.' }
format.json { render :show, status: :created, location: #movie }
else
format.html { render :new }
format.json { render json: #movie.errors, status:
:unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if #movie.update(movie_params)
format.html { redirect_to #movie, notice: 'Movie was successfully
updated.' }
format.json { render :show, status: :ok, location: #movie }
else
format.html { render :edit }
format.json { render json: #movie.errors, status:
:unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
#movie.destroy
respond_to do |format|
format.html { redirect_to movies_url, notice: 'Movie was successfully
destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_movie
#movie = Movie.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white
list through.
def movie_params
params.require(:movie).permit(:title, :director, :synopsis, :poster)
end
end
When I created the model using Rails scaffold I made the poster a string, but changed that to file in this section of Movies form partial:
<div class="field">
<%= form.label :poster %>
<%= form.file_field :poster, id: :movie_poster %>
</div>
Here is my routes file just in case I have made an error there:
Rails.application.routes.draw do
resources :movies
root 'movies#index'
# For details on the DSL available within this file, see
http://guides.rubyonrails.org/routing.html
end
Any help would be greatly appreciated.
uninitialized constant Movie::PosterUploader
You should generate the uploader. Do
rails generate uploader Poster
which should generate the file
app/uploaders/poster_uploader.rb
I am getting this error:
Paperclip::Errors::MissingRequiredValidatorError in ListingsController#create
Paperclip::Errors::MissingRequiredValidatorError
# POST /listings.json
def create
#listing = Listing.new(listing_params)
respond_to do |format|
if #listing.save
app/controllers/listings_controller.rb:27:in `create'
My listing.rb is
class Listing < ActiveRecord::Base
has_attached_file :image,
:styles => { :medium => "200x", :thumb => "100x100>"},
:default_url => "default.jpg",
:storage => :dropbox,
:dropbox_credentials => Rails.root.join("config/dropbox.yml")
end
My listings_controller.rb
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
# GET /listings
# GET /listings.json
def index
#listings = Listing.all
end
# GET /listings/1
# GET /listings/1.json
def show
end
# GET /listings/new
def new
#listing = Listing.new
end
# GET /listings/1/edit
def edit
end
# POST /listings
# POST /listings.json
def create
#listing = Listing.new(listing_params)
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render :show, status: :created, location: #listing }
else
format.html { render :new }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /listings/1
# PATCH/PUT /listings/1.json
def update
respond_to do |format|
if #listing.update(listing_params)
format.html { redirect_to #listing, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: #listing }
else
format.html { render :edit }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /listings/1
# DELETE /listings/1.json
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:name, :description, :price, :image)
end
end
Thanks for the help
its the new paperclip patch for rails 3
You have to add -
validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/jpg','image/png']
to your model where paperclip is used.
you can read more in this issue discussion:
https://github.com/galetahub/ckeditor/issues/399
To add to #rossmari's answer (which he is correct), there is a more generic way to validate for images, rather than just specifying each image type, which can get pretty cumbersome depending on what type of images you would like to allow.
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
I am just trying to do some really simple picture uploading using paperclip. I googled this issue and it seems like everyone else has much more complicated problem than simple uploads. Below are my models and controllers.
pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_attached_file :image
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
# validates the description
validates :description, presence: true
validates :user_id, presence: true
# validates paperclip
validates_attachment :image, presence: true,
content_type: { content_type: ["image/jpeg", "image/jpg", "image/png", "image/gif"]},
size: { less_than: 5.megabytes }
end
pin_controller.rb
class PinsController < ApplicationController
#before_filer will authentiate users to make sure they are logged in before doing anything with the Pins, with the except of indexing the pins so non-logged on users can also see them
before_filter :authenticate_user!, except: [:index]
before_action :set_pin, only: [:show, :edit, :update, :destroy]
# GET /pins
# GET /pins.json
def index
#pins = Pin.all
end
# GET /pins/1
# GET /pins/1.json
def show
end
# GET /pins/new
def new
# associate #pin to the current user's id
#pin = current_user.pins.new
end
# GET /pins/1/edit
def edit
# makes sure no other user can mess without a proper user id
#pin = current_user.pins.find(params[:id])
end
# POST /pins
# POST /pins.json
def create
# associate #pin to current user's id
#pin = current_user.pins.new(pin_params)
respond_to do |format|
if #pin.save
format.html { redirect_to #pin, notice: 'Pin was successfully created.' }
format.json { render action: 'show', status: :created, location: #pin }
else
format.html { render action: 'new' }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pins/1
# PATCH/PUT /pins/1.json
def update
# makes sure no other user can mess without a proper user id
#pin = current_user.pins.find(params[:id])
respond_to do |format|
if #pin.update(pin_params)
format.html { redirect_to #pin, notice: 'Pin was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
# makes sure no other user can mess without a proper user id
#pin = current_user.pins.find(params[:id])
#pin.destroy
respond_to do |format|
format.html { redirect_to pins_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
#pin = Pin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description, :image)
end
end
Here are what I think might be wrong with my code.
First, I followed the One Month Rails Tutorial, but since I am watching the outdated Rails 3 series, I have to convert everything he teaches into Rails 4 by myself through research. I may have set up the strong parameters wrong in my pin.rb controller. I added :image attribute field to the pin_params method like so
params.require(:pin).permit(:description, :image)
is this the right way to add :image using strong parameters? In rails 3, he added :image within attr_accessible
Second, in the README for paperclip, it says I should run which convert and ultimately input this line in my config file
Paperclip.options[:command_path] = "/usr/local/bin/"
Since I am using a windows machine, this is what I got ultimately after looking answers for hours
Paperclip.options[:command_path] = "C:/Program Files/ImageMagick-6.8.9-Q16/"
does the above path looks relatively correct for windows?
I too use Windows and was getting this error. I found my answer here. From what I gather, Paperclip protects against spoofing by getting the server's OS to validate the file's MIME type. It does this by executing the following command:
file -b --mime <my_file_name.extension>
The trouble is, the standard Windows Command Line doesn't have the file command, so the spoofing check fails and Paperclip throws the error that you observed.
To resolve this issue:
Install File for Windows.
Edit your system's PATH variable so that it includes the "File for Windows" bin directory path. (For me, it was C:\Program Files (x86)\GnuWin32\bin.)
Restart your Command Line, Git Bash, or what have you because you edited your PATH variable.
Confirm that Windows Command Line now responds to the file command.
This method worked for me on Windows 8.1 with Paperclip 4.2.1.
In your pin.rb Delete this line
validates_attachment :image, presence: true,
content_type: { content_type: ["image/jpeg", "image/jpg", "image/png", "image/gif"]},
size: { less_than: 5.megabytes }
Because your already use
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
I also do One More Rails with the outdated videos,like you.
Check for errors from my project
Here is the link My GigHub Project Files
Good Luck!)
I'm trying to develop a app in Ruby on Rails 4.0 (already used older versions of this incredible framework) and I having some troubles.
I installed the FriendlyID gem and I think everything is okay, but I'm receiving errors when I try to test my app.
If I go to http://0.0.0.0:3000/categories/1, this works. But when I click in "edit" in this page, or just go to http://0.0.0.0:3000/categories/electronics (that's the slugged name of category with ID 1), I receive the following error:
Couldn't find Category with id=electronics
# Use callbacks to share common setup or constraints between actions.
def set_category
#category = Category.find(params[:id]) #Here's pointed the error
end
Category Model:
class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
# Validations
validates_uniqueness_of :name, :case_sensitive => false
end
Category Controller:
(generated by scaffold for test purposes)
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
#categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
#category = Category.new
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
#category = Category.new(category_params)
respond_to do |format|
if #category.save
format.html { redirect_to #category, notice: 'Category was successfully created.' }
format.json { render action: 'show', status: :created, location: #category }
else
format.html { render action: 'new' }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if #category.update(category_params)
format.html { redirect_to #category, notice: 'Category was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
#category.destroy
respond_to do |format|
format.html { redirect_to categories_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
#category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:name)
end
end
Migration:##
(I added friendlyId after create the Category table, but I think is okay)
class AddColumnToCategory < ActiveRecord::Migration
def change
add_column :categories, :slug, :string
add_index :categories, :slug, unique: true
end
end
Routes:
resources :categories
Hope you can help me. What I'm doing wrong in Rails 4.0?
Check the doc, friendly id stopped hacking find method (for the greater good), you now have to do:
# Change Category.find to Category.friendly.find in your controller
Category.friendly.find(params[:id])
You can now use:
extend FriendlyId
friendly_id :name, use: [:finders]
in your model.