Rails 4 Active Admin Problems - ruby-on-rails

I am having two big problems with Active Admin
When I go to edit a user the encrypted password does not show so essentially i'm having to hack my own site and copy and paste another encrypted password in to the field to update the user - this is the same with create user.
The second issue is I cannot create a new user. When I go to create a user nothing happens. I don't get an error. The page just refreshes and the user does not save.
User.rb
ActiveAdmin.register User do
controller do
def permitted_params
params.permit!
end
end
end
I tried destroying my install of active admin and then I reinstalled it and generated the models again but same result. I'm using Rails 4.2.1 and Ruby 2.0.0.
gem 'activeadmin', github: 'activeadmin'
In development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
I tried changing config.cache_classes = false to true but that does not work either.
I'm not sure what to do here. Any suggestions? I take it this is a bug. Hope it can be fixed. Thanks.

It appears you're permitted_params method in your app/admin/user.rb file is unconventional and could be causing you problems. You need to add them like this and also put in :encrypted_password if you want to be able to change/edit it ...
ActiveAdmin.register User do
permit_params :email, :password, :password_confirmation, :encrypted_password
...
end

Related

Sitemap generators unable to generate sitemap

I have this website https://shopus.pk. I am unable to generate sitemaps using Sitemap generator tools. They just give error like "Error: 422 Unprocessable Entity" or just give me only 1 URL like following:-
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
</urlset>
I understand there is some problem relating to probably security settings of the website or server. But please someone help me identifying the problem. Thanks
BTW my website is being hosted by dreamhost. But I don't think dreamhost has anything to do with this.
I have tried https://www.xml-sitemaps.com/ , http://www.web-site-map.com/, http://www.check-domains.com/sitemap/index.php , https://websiteseochecker.com/html-sitemap-generator/ and many more.
Also I downloaded and tried A1 Sitemap Generator, gnucrawlandmap, SiteMapBuilder, HSEO Sitemap Generator and a few more free sitemap generating tools.
All of the above websites or tools wither give access error or return with just 1 or 2 URLs.
Since my website is built on Ruby on Rails my config file for production environment is below:-
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :error
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: "https://shopus.pk" }
# configure action_mailer
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {}
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.asset_host = 'https://shopus.pk'
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
And this is how my application controller looks like:-
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
include ApplicationHelper
private
# Confirms a logged-in user.
def logged_in_customer
unless logged_in?
store_location
redirect_to login_url
end
end
end
Let me know if you require anything else to solve this issue.
Ok looks like I have figured out the problem. But still not sure about it.
So after miserably failing with trying almost every site map generator I decided to create my own sitemap generator using Ruby Gems Nokogiri and Mechanize. But to my surprise whenever I would try to extract HTML code from my website the same error would show up "422 Unprocessable Entity". This was the exact error message which I was getting from a few Site map generators.
I removed "protect_from_forgery with: :exception" from Applications controller and the sitemap generators started working on my website.
But this wasn't right because "protect_from_forgery with: :exception" should be there. And I have 2 other websites with "protect_from_forgery with: :exception" included in the Application controllers. Sitemap Generators don't show any problem working with these 2 websites.
The only difference between my first website and the other 2 was that my first website was using ajax and the other 2 were simple. So i finally I figured out that when I remove the format.js line from
respond_to do |format|
format.js
format.html
end
code block from my index action in the main controller, things would start working. Later I realized that I should have written the respond_to code with format.js below format.html like this
respond_to do |format|
format.html
format.js
end
After this I changed all respond_to code in every action of all controllers with format.html above format.js
Everything is working fine now.
However I am still confused and not sure if my identification of the cause of problem is right? I am still a novice programmer. Also I fail to understand why the order of format.html and format.js matter in this case.
I am open to all suggestions and a little more insight into the problem.

Session ID changes when I make a POST request in Rails but only during tests

I'm having a rather odd issue in that POST requests triggered by link_to with method: :post. In the test environment the session_id seems to change. This causes issues such as the current_user object doesn't exist within the action I'm posting too. I've logged out the request and the session info and I can see that the session has changed for the POST action and when I try to use current_user the test fails.
I have other POST requests through forms around the app. And they work fine. It seems to be some Rails magic around the link_to with method: :post and passing the CSRF token.
I'm able to get around this by changing my test.rb to be the same as my development.rb. But I'm sure this isn't a good solution. It's possible it's related to some configuration but it seems like this is the default behavior.
Controller
class RecruitersController < ApplicationController
before_action -> { STDOUT.puts "Request: #{request.method} #{request.fullpath}" }
before_action -> { STDOUT.puts "Session: #{session[:session_id]}" }
...
end
Button that triggers the POST Request
= link_to "<3", recruiter_request_url(id: recruiter.id), method: :post, remote: true
Output in Tests
Request: GET /recruiters/dashboard
Session: ee8c577fdf6d1714c2a837f0890e0294
Request: GET /recruiters/premium
Session: ee8c577fdf6d1714c2a837f0890e0294
Request: POST /recruiters/request_premium_trial/1
Session: 314c6eef0156aa36a469a4f9ea7513a8
Output in Development
Request: GET /recruiters/dashboard
Session: cdb333efb5d62e6ddbb5914c8edd7a92
Request: GET /recruiters/premium
Session: cdb333efb5d62e6ddbb5914c8edd7a92
Request: POST /recruiters/request_premium_trial/1
Session: cdb333efb5d62e6ddbb5914c8edd7a92
The Spec
Simple spec user signs in goes to the dashboard, goes to the premium page and then clicks on the link that makes the POST request.
scenario 'Should be able to make request', js:true do
rsign_in # Function that simulates sign in
click_on 'Premium'
click_on '<3'
assert_text 'Request made' # Fails as we're redirected to sign in page when we try to authenticate the user
end
Test.rb
Rails.application.configure do
# Set log level
config.log_level = :debug
# This means that all URLs need to have 5 parts to them. This is for http://recruiter.127.0.0.1.xip.io:3000
config.action_dispatch.tld_length = 5
# Settings specified here will take precedence over those in config/application.rb.
cache_store = :file_store, "tmp/cache"
# Use a different job queue
config.active_job.queue_adapter = Figaro.env.job_queue.to_sym if Figaro.env.job_queue?
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = true
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_controller.default_url_options = { host: 'localhost:5000' }
config.action_mailer.default_url_options = { host: 'localhost:5000' }
config.action_mailer.delivery_method = :test
# config.action_mailer.delivery_method = :smtp
# config.action_mailer.smtp_settings = { address: 'localhost', port: '1025' }
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
config.active_record.raise_in_transactional_callbacks = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.preview_path = "#{Rails.root}/app/mailers/previews"
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: 'localhost', port: '1025' }
config.cache_store = :dalli_store
# Use a different job queue
config.active_job.queue_adapter = Figaro.env.job_queue.to_sym if Figaro.env.job_queue?
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.after_initialize do
Bullet.enable = false
Bullet.alert = true
Bullet.console = true
Bullet.rails_logger = true
end
end
Seems like the error was coming from this line in my test.rb, was just trying to set the default host on my links to not be example.com. Not sure how this resulted in the bug I was experiencing. But after going through the config and trying to figure out why development.rb was working. This is what I got.
config.action_controller.default_url_options = { host: 'localhost:5000' }
Thanks to everybody who helped me.

"Unable to autoload constant User" error when changed code in development

I have a problem with my rails application. After an Update from Rails 3 to 4.
When I surf through the pages after starting the server in development mode everything is fine.
But after a single code change (even adding a space) every page request shows the following error.
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
The file lives exactly there and defines the class:
class User < ActiveRecord::Base
…
I tried many things with config.autoload_paths and config.eager_load_paths in application.rb but with no luck.
Deactivating spring did not help either.
Developing an app and having to restart the server after every single change seems so 90s.
$ rails -v
Rails 4.2.4
$ ruby -v
ruby 2.1.7p400 (2015-08-18 revision 51632) [x86_64-linux]
Some relevant configs:
development.rb
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
end
application.rb
module Serviceportal
class Application < Rails::Application
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
[… some asset precompile stuff …]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"
]
config.eager_load_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"]
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Berlin'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :de
[… some SQL and active support stuff …]
config.action_controller.include_all_helpers = false
config.action_controller.action_on_unpermitted_parameters = :raise
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
Edit: The error mostly shows up in lib/auth/user_proxy.rb in the following function. Maybe this helps to narrow the range of possible causes.
def self.usertype_allowed?(type)
[ User, TempCustomer ].include? type.classify.safe_constantize rescue false
end
Edit 2: Stringify the class names in Edit 1 helped (thanks #Benjamin Sinclaire). But only leads to the next errors. I could also avoid using classes. But at the following error in app/controllers/concerns/security.rb there is nothing can change?
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
code:
def set_current_user
User.current = current_user
end
with current user saved in the Thread (code from /path/to/my/rails-app/app/models/user.rb
def self.current
Thread.current['current_user']
end
def self.current=(user)
Thread.current['current_user'] = user
end
Just to make it clear again: It works after server restart in development until I change some code somewhere.
1 See if you have any multiple-level class or module declaration done one one line and change them to be declared in several lines.
Instead of
class Parent::Sub::Child
end
Do
module Parent
module Sub
class Child
end
end
end
2 Check your model association definitions, and ensure you are never using constant. Use string instead.
Instead of
belongs_to :manager, class_name: User
Do
belongs_to :manager, class_name: 'User'
3 Just saw your edit. Can you refactor like this?
# I assume `type` is a string or such, so we can compare classes
# names instead of constants, and get rid of `safe_constantize`
def self.usertype_allowed?(type)
['User', 'TempCustomer'].include? type.classify rescue false
end
4 Not a good idea to serialize an active record object in the Thread storage. Change it to store the user id instead, like this:
def set_current_user
User.current = current_user.id
end
def self.current
Thread.current['current_user_id']
end
def self.current=(user_id)
Thread.current['current_user_id'] = user_id
end
You don't need include app/models/concerns and app/controllers/concerns in your autoload/ eagerload paths as they are included by default in Rails 4: https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns
Also make sure that your concerns are defined as modules, extend ActiveSupport::Concern and with the appropriate file name
#taggable.rb
module Taggable
extend ActiveSupport::Concern
end
Another cause of your problem might be that some modules/ classes in app/decorators/concerns, lib, lib/shared are using the User class
which is not loaded yet or some of it's dependencies are not loaded so try adding require_relative path_to_user.rb at the top of those files
-----Edit-------
Try adding at the top of lib/auth/user_proxy.rb
require_dependency 'app/models/user'
This way you'll remove any ambiguity in autoloading the User class and you won't mess around with Rails autoloading see more here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#require-dependency , http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#common-gotchas
Same problem but in an engine w/ namespaces. No issues in production or in development until a code-change / autoload.
The solution was to
checking for double definitions (there were none)
checking if the module nesting strictly follows rails conventions in the filesystem.
I've had myns under myengine/app/myns/subns/obj.rb but myns is being ignored as it is at the root of the app folder, so moving the myns folder into a subfolder myengine/app/lib/myns solved the issue.
Note: the rails error message was very explicit about the module nesting (while still pointing to the wrong .rb file in the filesystem) so look closely at the error. The error was 'Unable to autoload constant subns/obj.rb in .../myns/subns/obj.rb'. Rails suggesting the incorrect file-location (which exists) is misleading in this case.
During a Rails/Ruby Update I found time to look into this and finally found the cause.
The user class had an unloadable in it for years. That caused the problems since Rails 4. Now I removed this and found no issues after that.

Assets compiling on fly (Rails with compass gem)

I am trying to change my styles of my scss assets on my ruby on rails project but they are applying just after rake assets:precompile and restarting rails server.
With JS files everything allright and they are changing on fly.
Possible problem is with compass gem.
That is my repo - https://github.com/tanotify/blog
And file development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
Found solution! In config/environments/development.rb added line:
config.serve_static_assets = false

rails custom_configuration gem produces empty orderedoptions

Ruby 2.1.5
Rails 4.0.13
Using the custom_configuration gem, I get unexpected results.
config/environments/development.rb
JumboSIP::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
module Devise
module LdapAdapter
def self.valid_credentials?(login, password)
return true
end
end
end
config.cache_store = :memory_store
config.log_level = :debug
config.assets.compile = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
[..etc]
# ------------------------------------
# Application-specific configuration
# ------------------------------------
# use active directory auythentication (only for production)
config.x.use_ad_auth = false
# Enable to create cockpit cache files
config.x.cockpit_cache_enabled = false
config/initializers/scheduler.rb
if Rails.configuration.x.cockpit_cache_enabled
Rails.logger.info 'Initializing Cockpit Cache Scheduler'
puts 'Initializing Cockpit Cache Scheduler'
The code in the if is reached while it should not.
Debug inspection shows that
Rails.configuration.x.cockpit_cache_enabled evaluates to Empty ActiveSupport:OrderedOptions.
Rails.configuration.x is of type CustomConfiguration::Configuration
I checked I am actually in development environment.
Any clue as to why this happens? Any conflicts with other gems?
If I uses orderedoptions outside this gem, behaviour is as expected
It's two months delayed, but I ran into the same issue. The custom_configuration gem expects the options to be namespaced under another hash. Instead of:
config.x.cockpit_cache_enabled = false
try:
config.x.cockpit.cache_enabled = false
Now you should be able to access the value with:
Rails.configuration.x.cockpit.cache_enabled

Resources