Paperclip in Rails 4 - Strong Parameters Forbidden Attributes Error - paperclip

Having a problem with a Paperclip upload in Rails 4 - failing on ForbiddenAttributesError (strong parameters validation). Have the latest paperclip gem and latest rails 4 gems.
I have a model "Image" with an attached file "upload" in the model:
has_attached_file :upload, :styles => { :review => ["1000x1200>", :png], :thumb => ["100x100>", :png]}, :default_url => "/images/:style/missing.png"
The image model was created with a scaffold, and I added paperclip migrations. The form partial was updated to use
f.file_field :upload
the form generates what appears to be a typical set of paperclip params, with the image param containing the upload. I am also passing a transaction_id in the image model, so it should be permitted. But that's it - the image and the transaction ID.
I expected to be able to write the following in my controller to whitelist my post - but it failed:
def image_params
params.require(:image).permit(:transaction_id, :upload)
end
So I got more explicit - but that failed too:
def image_params
params.require(:image).permit(:transaction_id, :upload => [:tempfile, :original_filename, :content_type, :headers])
end
I'm a bit frustrated that Rails 4 is not showing me what ForbiddenAttributesError is failing on in a development environment - it is supposed to be showing the error but it does not - would be a nice patch to ease development. Or perhaps everyone else is getting something that I am missing! Thanks much for the help.

I understand what happened here now - and will leave this up in the hope it helps someone else. I was porting code from a rails 3 project and missed the line that created the image:
#image = current_user.images.new(params[:image])
In rails 4 this is incorrect (I beleive). I updated to
#image = current_user.images.new(image_params)
and that solved my problem.

It looks like your first one should have worked. This is what I use for my projects.
class GalleriesController < ApplicationController
def new
#gallery = Gallery.new
end
def create
#user.galleries.new(gallery_params)
end
private
#note cover_image is the name of paperclips attachment filetype(s)
def gallery_params
params.require(:gallery).permit(:cover_image)
end
end

Related

Record Not Found rails 5 ActiveRecord Error

I am trying to use a vanity URL that uses the SecureRandom issued ident to a culvert, and then display that culvert via the show page.
This is a screenshot of the error message:
This is a screenshot of the browser url:
My Culvert Controller is:
I have tried Both:
#culvert = Culvert.find_by_culvert_ident(params[:id])
AND
#culvert = Culvert.find_by_id(params[:culvert_ident])
In my culvert controller show action, both yield the same result (screenshot)
private
# Use callbacks to share common setup or constraints between actions.
def set_culvert
#culvert = Culvert.find_by_culvert_ident(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def culvert_params
params.require(:culvert).permit(:culvert_ident, :latitude, :longitude, :address, :user_id)
end
This is my Culvert Model ident generator and vanity url methods:
before_create :generate_culvert_ident
# Relationships
belongs_to :user
# Model Validations
validates_uniqueness_of :culvert_ident
# Ident Generator
def generate_culvert_ident
begin
self.culvert_ident = SecureRandom.hex(3).upcase
other_culvert = Culvert.find_by(culvert_ident: self.culvert_ident)
end while other_culvert
end
# Url Direction
def to_param
culvert_ident
end
So my goal is to create the culvert, auto assign a unique identifier, save it and display the culvert using the custom identifier as opposed to the standard 1,2,3,4 id's
this works in another web app i have used, is setup exactly the same but i am getting this error here and cant figure out why. Please let me knwo if you require further info!
**
EDIT # 1 - Adds Screenshot of Console output
**
So the issue here was that I removed the culverts controller
before_action :set_culvert
as soon as I re-added the set_user action the issue was resolved.
thanks for your assistance!

ruby on rails 3.1 global exception handler

I'm developing an app with Rails 3.1.2 but I can't find some documentation that works with errors / exception (like 404) on this version of rails.
i have tried things like:
In application controller
rescue_from ActiveRecord::RecordNotFound,ActionController::RoutingError,
ActionController::UnknownController, ActionController::UnknownAction, :NoMethodError, :with => :handle_exception
def handle_exception
render :template => 'error_pages/error'
end
environment/development.rb
config.consider_all_requests_local = false
Where can I find a solution?
Thanks in advance...
This should work:
In application controller
class NotFound < StandardError; end
rescue_from NotFound, :with => :handle_exception
def handle_exception
render :template => 'error_pages/error'
end
Look at action_dispatch/middleware/show_exceptions.
From the documentation in the source:
# This middleware rescues any exception returned by the application
# and wraps them in a format for the end user.
Short story short, it renders ActionDispatch::ShowExceptions.render_exception when the wrapped application (Rails, in your case), encounters an unrescued exception.
If you look through the default implementation, it ends up rendering something like public/500.html, which is what you see in the production environment. Overwrite the method or method chain it as you see fit to add your own implementation.

Rails 3 AJAX: wrong constant name

I am trying to do Ajax login with Devise, as explained here: http://jessehowarth.com/2011/04/27/ajax-login-with-devise#comment-5 (see comment from jBeasley).
My controller is attempting to return
class Users::SessionsController < Devise::SessionsController
def failure
render :json => {:success => false, :errors => ["Login failed."]}
end
end
which results in this error:
NameError (wrong constant name ["{\"success\":false,\"errors\":[\"Login failed.\"]}"]Controller):
and Firebug showing [500 Internal Server Error].
How can I fix this? I am running Rails 3.1 and devise 1.4.5.
Thanks!!
Did you do the step recommended by Jeff Poulton in comment #4? The :recall option in 1.4.5 looks to be completely incompatible to older versions. It now requires you send the controller, whereas in the tutorial you're following he just sends the action (the old way).
In your case, :recall => :failure must be changed to :recall => "users/sessions#failure" in Devise 1.4.5.
This is because of the way the controller for the failure action is determined. In older versions, it was simply pulled from the params.
def recall_controller
"#{params[:controller]}.camelize}Controller".constantize
end
# called via recall_controller.action(warden_options[:recall]).call(env)
In 1.4.5, it expects a string specifying the controller and action, in the style of routes:
def recall_app(app)
controller, action = app.split('#')
controller_name = ActiveSupport::Inflector.camelize(controller)
controlller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
controller_klass.action(action)
end
# called via recall_app(warden_options[:recall]).call(env)
It would seem as though your app is actually passing the JSONified hash of options to recall_app, which, lacking a '#', isn't being split, and the entire string is concatenated to "Controller" to attempt to ascertain the failure controller's class.
You are missing the return in
def failure
return render:json => {:success => false, :errors => ["Login failed."]}
end
Does that make a difference?

Why isn't my custom homepage appearing after deleting public/index.html?

I am trying to get my customized home page to appear instead of the Welcome Aboard You're Riding Ruby on Rails default page. In my config/routes.rb file I have the line root :to => 'pages#home' to let it load the pages/home.html.erb file, and I removed public/index.html as instructed in the comments of the routes.rb file. All the other web pages which I used the syntax match "/page_name", :to => "pages#page_name" are working fine. What more do I need to do to update my home page?
EDIT:
Someone asked me to post my pages controller. Here it is:
class PagesController < ApplicationController
def home
#title = "Home"
end
def contact
#title = "Contact"
end
def about
#title = "About"
end
def help
#title = "Help"
end
end
The #title variable is referred to in my .html.erb files, but otherwise my controller is pretty much empty.
Have you tried restarting the server after deleting index.html? Did you clear your browser cache?
Do you have a PagesController?
rails generate controller pages home
The syntax I use (Rails 2.3) is:
map.root :controller => "welcome"
That goes to the :index method. If you want to go to :home, I presume you would add :action.

How to use Sinatra, Datamapper, DM-Paperclip and S3?

Update: I've switched to CarrierWave (finally got it to work), so although I still appreciate answers to this question I won't be able to try if they actually work since I've completely removed DM-Paperclip from my code.
Hi there,
I'm developing a Sinatra-webapp using DataMapper and are now looking to add some upload-functionality with S3 as storage. I've tried CarrierWave, but I couldn't get that to work so now I'm trying dm-paperclip. This is what I have right now:
Model:
class Article
include DataMapper::Resource
include Paperclip::Resource
property :id, Serial
property :created_at, DateTime
property :updated_at, DateTime
property :title, String
property :body, Text
has_attached_file :screenshot,
:storage => :s3,
:s3_credentials => {
:access_key_id => 'my-access-key-id',
:secret_access_key => 'my-secret_access-key',
:bucket => 'my-bucket'
},
:styles => {
:medium => "300x300>",
:thumb => "100x100>"
}
end
Controller:
post '/articles/create' do
#article = Article.new
#article.title = params[:title]
#article.body = params[:body]
#article.screenshot = params[:screenshot]
begin
#article.save
rescue DataMapper::SaveFailureError => e
puts "Error saving article: #{e.to_s} validation: #{#article.errors.values.join(', ')}"
rescue StandardError => e
puts "Got an error trying to save the article #{e.to_s}"
end
redirect '/articles'
end
Yet when I create a new article it doesn't save anything to my S3 bucket and I don't get any errors either.
Any ideas what I'm doing wrong?
Hey! Please try my fork: https://github.com/solnic/dm-paperclip it includes many patches which have fixed some issues with S3. Within a month or two I will be releasing it.
Apart from the solutions already posted, I would like to add a recomendation.
In my experience, using DataMapper's raise_on_save_failure feature is not of much help for debugging options. I recommend you disable that feature and use something like the following code:
if model.save then
return model
else
error = String.new
model.errors.each do |e|
error << "#{e[0]}\n"
end
raise ArgumentError, error
end
That way, you will get a full explanation of every issue DM encountered when trying to persist your model. I find it very useful not only for debugging but also for showing those messages to the consumers of my application.
Some time ago I did my fork especially for S3 in mind. My fork work with official AWS-SDK, instead of old aws-s3 which is mostly outdated.
If anybody will search for S3 solution for paperclip this is one that work (today)
https://github.com/krzak/dm-paperclip-s3
take a look at readme to get how to configure paperclip for S3

Resources