Rails where syntax change from Rails 3 to 4? - ruby-on-rails-3

In Rails 3, I have this code:
def self.active
includes(configuration_slots: [:configuration])
.where("configurations.is_active = 't'")
end
Is this not allowed anymore in Rails 3? Why not? What's the reason?
I have to write this now:
where(configurations: { is_active: true })

Related

ActiveAdmin error 401 Can no longer log in with working credentials. Using rails 5.2

I created an ActiveAdmin user and I can no longer log on using any of my previous ActiveAdmin users nor can I create a new one. When I try, I get a 401 error. I have tried multiple times to manipulate the devise initializer and the model to no avail.
Using rails 5.2.1,activeadmin 1.3.1, activeadmin_addons 1.6.0, cancancan 2.2.0
active_admin_role 0.2.1
Processing by ActiveAdmin::Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEpX4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>"hodari#hiddengeniusproject.org", "password"=>"[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
AdminUser Load (1.1ms) SELECT "admin_users".* FROM "admin_users" WHERE (lower(email) = 'hodari#hiddengeniusproject.org') ORDER BY "admin_users"."id" ASC LIMIT $1 [["LIMIT", 1]]
Completed 401 Unauthorized in 149ms (ActiveRecord: 1.9ms)
Processing by ActiveAdmin::Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEp X4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>" ", "password"=>"
[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
Rendering /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/shared/_links.erb (1.6ms)
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out (51.6ms)
Completed 200 OK in 838ms (Views: 836.8ms | ActiveRecord: 0.0ms)
Here is my adminuser model
class AdminUser < ApplicationRecord
role_based_authorizable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable
attr_accessor :login
has_many :classrooms
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
where(conditions).where(["lower(email) = :value", { :value => login
}]).first
end
end
and here is my devise.rb
Devise.setup do |config|
config.secret_key = ENV['devise_secret_key'] if Rails.env.production?
config.mailer_sender = 'Devise Omniauth
config.mailer = 'Devise::Mailer'
config.parent_mailer = 'ActionMailer::Base'
config.authentication_keys = [:login]
config.reset_password_keys = [:login]
config.strip_whitespace_keys = [:email, :username ]
config.params_authenticatable = true
config.http_authenticatable = false
config.paranoid = true
config.skip_session_storage = [:http_auth]
config.clean_up_csrf_token_on_authentication = true
config.reload_routes = true
config.stretches = Rails.env.test? ? 1 : 11
config.allow_unconfirmed_access_for = 364.days
config.confirm_within = 365.daysconfig.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 6..128
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
config.unlock_strategy = :both
config.reset_password_within = 6.hours
Rails.application.config.app_middleware.use OmniAuth::Builder do
config.omniauth :google_oauth2,
Figaro.env.google_client_id,
Figaro.env.google_client_secret
#google_oauth2_options
{
scope: 'email, calendar',
prompt: 'select_account',
image_aspect_ratio: 'original',
name: 'google',
access_type: 'offline',
provider_ignores_state: true
}
end
end
I'm am not sure what else to include, I am still learning.
thank you
I just went back into my git repository to the last known working version and reset to there. Not sure what the problem was but my app is working again.

template.path_without_format_and_extension Not working in rails 3.0.3. Getting undefined method template

I am using i18n in rails 3.0.3 and user have functionality to edit text. If user save text then it comes from database instead of en.yml file. I have override t helper like below:
def c_t(key, options = {})
c_key = (scope_key_by_partial_custom(key)).gsub(".","_")
if $LAYOUT_CONTENTS[c_key].present?
$LAYOUT_CONTENTS[c_key]
else
t(key,options)
end
end
and then
def scope_key_by_partial_custom(key)
if key.to_s.first == "."
template.path_without_format_and_extension.gsub(%r{/_?}, ".") + key.to_s
else
key
end
end
I am calling this method from view:
<h1 <%= c_t '.title' %></h1>
It was working fine in rails 2.3 but after upgrading rails to 3.0.3 I am getting error
**undefined method `template' for Class
use this helper method in rails 3
view_context.instance_variable_get(:#_virtual_path)

Rails 5.1.3 API using Devise Auth Token custom rendering

I'm developing an API using Rails 5.1.3 and I'm using the gem devise_token_auth for authenticate. Everything was working fine until I needed to customize the JSON renderized after an error occurred, like the client sending an request with an invalid email.
So, to do this, I redefined my routes from
mount_devise_token_auth_for 'User', at: 'auth'
to
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
registrations: 'devise/registrations'
}
and created a file app/controllers/devise/registrations_controller.rb as below:
class RegistrationController < DeviseAuthToken::RegistrationController
def render_create_error
render 'devise/registrations/create_error.json'
end
def render_create_success
super
end
end
Now all requests that depends of RegistrationController are getting this error:
ActionView::Template::Error:
undefined method `protect_against_forgery?' for #<#<Class:0x007f84cfab70d8>:0x007f84cec53e10>
What I should do to fix this error?
Thanks in advance!
This is what I did on my rails server (rails 6). I have created folders called overrides where I place all my custom controllers / views
routes.rb
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
registrations: 'overrides/registrations'
}
app/controllers/overrides/registrations_controller.rb
module Overrides
class RegistrationsController < DeviseTokenAuth::RegistrationsController
def render_create_success
render partial: 'overrides/registrations/render_create_success.json.jbuilder'
end
end
end
app/views/overrides/registrations/_render_create_success.json.jbuilder
json.status 'success'
json.data do
json.extract! #resource, :field1, :field2, etc.
end

Paperclip and Phusion Passenger NoHandlerError

I followed this guide to get drag and drop file uploads through AJAX: http://dannemanne.com/posts/drag-n-drop_upload_that_works_with_ror_and_paperclip
Everything was working fine on my development environment with WebBrick but if I deploy to PhusionPassenger then I get:
Paperclip::AdapterRegistry::NoHandlerError (No handler found for #<PhusionPassenger::Utils::RewindableInput:0x000000041aef38 #io=#<PhusionPassen...
I'm using this in my controller:
before_filter :parse_raw_upload, :only => :bulk_submissions
def bulk_submissions
...
#submission = Submission.create!(url: "", file: #raw_file, description: "Please edit this description", work_type: "other", date_completed: DateTime.now.to_date)
...
end
private
def parse_raw_upload
if env['HTTP_X_FILE_UPLOAD'] == 'true'
#raw_file = env['rack.input']
#raw_file.class.class_eval { attr_accessor :original_filename, :content_type }
#raw_file.original_filename = env['HTTP_X_FILE_NAME']
#raw_file.content_type = env['HTTP_X_MIME_TYPE']
end
end
Looking at the request itself all the headers are set (X_MIME_TYPE, X_FILE_NAME) etc.
Any ideas?
Thanks in advance!
The example you're cribbing from expects the file stream to be a StringIO object, but Passenger is giving you a PhusionPassenger::Utils::RewindableInput object instead.
Fortunately, a RewindableInput is duckalike to StringIO for this case, so Paperclip's StringioAdapter can be used to wrap your upload stream.
Inside the if block in your parse_raw_upload, at the end, do:
if #raw_file.class.name == 'PhusionPassenger::Utils::RewindableInput'
#raw_file = Paperclip::StringioAdapter.new(#raw_file)
end

Paperclip- validate pdfs with content_type='application/octet-stream'

I was using paperclip for file upload. with validations as below:
validates_attachment_content_type :upload, :content_type=>['application/pdf'],
:if => Proc.new { |module_file| !module_file.upload_file_name.blank? },
:message => "must be in '.pdf' format"
But, my client complained today that he is not able to upload pdf. After investigating I come to know from request headers is that the file being submitted had content_type=application/octet-stream.
Allowing application/octet-stream will allow many type of files for upload.
Please suggest a solution to deal with this.
Seems like paperclip doesn't detect content type correctly. Here is how I was able to fix it using custom content-type detection and validation (code in model):
VALID_CONTENT_TYPES = ["application/zip", "application/x-zip", "application/x-zip-compressed", "application/pdf", "application/x-pdf"]
before_validation(:on => :create) do |file|
if file.media_content_type == 'application/octet-stream'
mime_type = MIME::Types.type_for(file.media_file_name)
file.media_content_type = mime_type.first.content_type if mime_type.first
end
end
validate :attachment_content_type
def attachment_content_type
errors.add(:media, "type is not allowed") unless VALID_CONTENT_TYPES.include?(self.media_content_type)
end
Based on the above, here's what I ended up with which is compatible with PaperClip 4.2 and Rails 4:
before_post_process on: :create do
if media_content_type == 'application/octet-stream'
mime_type = MIME::Types.type_for(media_file_name)
self.media_content_type = mime_type.first.to_s if mime_type.first
end
end
For paperclip 3.3 and Rails 3, I did this a bit differently
before_validation on: :create do
if media_content_type == 'application/octet-stream'
mime_type = MIME::Types.type_for(media_file_name)
self.media_content_type = mime_type.first if mime_type.first
end
end
validates_attachment :media, content_type: { content_type: VALID_CONTENT_TYPES }
By the way, i needed to do this because testing with Capybara and phantom js using attach_file did not generate the correct mime type for some files.