I'm running Rails 3.2 and the latest version of Authlogic. When I run my app locally on my Mac, it works fine. When I try to run it on my production server (Ubuntu with Passenger/Apache), I get this:
You must establish a database connection before using acts_as_authentic
I'm not sure how to troubleshoot the problem. I posted this related question earlier today before I realized that the problem was broader than I thought.
I figured out the problem. Look at this snippet from Authlogic's lib/authlogic/acts_as_authentic/base.rb:
private
def db_setup?
begin
column_names
true
rescue Exception
false
end
end
If column_names throws an error, db_setup? will return false. Look at this other function, also from base.rb:
def acts_as_authentic(unsupported_options = nil, &block)
# Stop all configuration if the DB is not set up
raise StandardError.new("You must establish a database connection before using acts_as_authentic") if !db_setup?
raise ArgumentError.new("You are using the old v1.X.X configuration method for Authlogic. Instead of " +
"passing a hash of configuration options to acts_as_authentic, pass a block: acts_as_authentic { |c| c.my_option = my_value }") if !unsupported_options.nil?
yield self if block_given?
acts_as_authentic_modules.each { |mod| include mod }
end
If db_setup? returns false, Authlogic will throw an exception, but not the same exception thrown by column_names.
My problem was that column_names was throwing this exception:
/Users/jason/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1106:in `async_exec': PG::Error: ERROR: relation "users" does not exist (ActiveRecord::StatementInvalid)
LINE 4: WHERE a.attrelid = '"users"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
And the reason for THAT exception is that my user table is called user, not users, but Rails was not picking up on my pluralize_table_names setting properly. Once I fixed my pluralize_table_names problem (apparently the way this setting works has been changed in Rails 3.1), my Authlogic problem went away.
So if you're having this problem, you might want to try this:
Clone the Authlogic repo to somewhere on your dev machine
Change your Gemfile to use the local version of Authlogic ('authlogic', :path => '/path/to/authlogic')
Add a column_names call to db_setup? outside the begin/rescue/end clause
See if you get a different, potentially more accurate and informative, error, like I did
I've fixed this on my fork. Until Ben has time to merge the fix you can work around this using the fixed branch in your Gemfile;
gem 'authlogic', :git => 'git#github.com:james2m/authlogic.git', :branch => 'fix-migrations'
For anyone else who might have come to this page looking for an answer.
One reason could be that your haven't created your test database.
Just run:
$ RAILS_ENV=test rake db:create db:migrate
Follow the open issue at https://github.com/binarylogic/authlogic/issues/318 and +1 so the fix gets merged soon :)
Related
I am in the process of upgrading a rails 4.2 application to rails 5. One of the models uses an ActiveRecord::Store. When retrieving records after the upgrade, said store only returns an empty Hash. I have no idea why that's happening and wasn't able to find anything in the changelog. So any help and explanation would be appreciated.
Here's the output of the rails 4 console:
=> #<StoredDataQuery ..., config: {"start_date"=>6, "end_date"=>0, ...>
and rails 5:
=> #<StoredDataQuery ..., config: {}, ...
psql output:
development=# SELECT config FROM stored_data_queries WHERE id=1;
config
---------------------------------------------
--- !ruby/hash:ActionController::Parameters+
start_date: 6 +
end_date: 0 +
interval: day +
(1 row)
Looking at the SQL output, I'm suspecting it has something to do with the data being serialized as ActionController::Parameters.
Thanks for your help!
Here's how to fix it in sql (postgres):
UPDATE stored_data_queries SET config = replace(config, 'ActionController::Parameters', 'ActiveSupport::HashWithIndifferentAccess');
Same here, after Upgrading Zammad from Rails 4.2 to Rails 5.0. After some research I found out that active record is only reading ActiveSupport::HashWithIndifferentAccess from store anymore (other classes are skipped).
So for migration you can overwrite ActiveRecord::Store::IndifferentCoder.as_indifferent_hash in a migration, read all related records from database and just save them back (then all ActionController::Parameters are converted to ActiveSupport::HashWithIndifferentAccess).
For me the following migration (under Rails 5.0) has worked to convert all ActionController::Parameters to ActiveSupport::HashWithIndifferentAccess:
require 'active_record/store'
module ActiveRecord
module Store
class IndifferentCoder
def self.as_indifferent_hash(obj)
case obj
# re-enable using ActionController::Parameters in stores,
# convert them to ActiveSupport::HashWithIndifferentAccess
# at reading from db
when ActionController::Parameters
obj.permit!.to_h
# /re-enable
when ActiveSupport::HashWithIndifferentAccess
obj
when Hash
obj.with_indifferent_access
else
ActiveSupport::HashWithIndifferentAccess.new
end
end
end
end
end
class FixedStoreUpgrade45 < ActiveRecord::Migration[5.0]
def up
[Macro, Taskbar, Calendar, Trigger, Channel, Job, PostmasterFilter, Report::Profile, Setting, Sla, Template].each do |class_name|
class_name.all.each do |record|
begin
record.save!
rescue => e
Rails.logger.error "Unable to save/update #{class_name}.find(#{record.id}): #{e.message}"
end
end
end
end
end
Raise notice is typically used to debug PSQL scripts in postgres (link).
The docs say that there's some kind of support for printing notices when using the pg gem, but there's no info on how to use this proc, what it yields, possible (probable?) caveats etc.
Does anyone have a working code example for production and/or development? Ideally, I'm looking for a solution that allows PG notices to be printed out in development when Sequel logging is enabled.
When I do:
DB = Sequel.connect(
ENV['DATABASE_URL'],
notice_receiver: lambda{ |x| binding.pry }
)
the notice_receiver lambda never gets called once I execute a function that raises a notice. I.e
[1] pry(#<Psql::CalculateMasterBalancesTest>)> DB.select{ |o| Sequel.function(:emit_notice) }.first
I, [2017-05-17T16:51:56.746003 #23139] INFO -- : (0.000335s) SELECT emit_notice() LIMIT 1
=> {:emit_notice=>""}
where emit notice is:
CREATE OR REPLACE FUNCTION emit_notice()
RETURNS VOID AS $$
BEGIN
RAISE NOTICE 'NOTICE ME!!!';
END;
$$ LANGUAGE plpgsql;
and it works from PgAdmin:
NOTICE: NOTICE ME!!!
Total query runtime: 21 ms.
1 row retrieved.
UPDATE
Alejandro C gave a good working example, and it seems that notices don't get distributed with the notice_receiver hook. For example:
Sequel.connect(DB.opts.merge(:notice_receiver=>proc{|r| puts r.result_error_message})){ |db|
db.do("BEGIN\nRAISE NOTICE 'foo';\nEND;")
}
prints nothing, and:
Sequel.connect(DB.opts.merge(:notice_receiver=>proc{|r| puts r.result_error_message})){ |db|
db.do("BEGIN\nRAISE WARNING 'foo';\nEND;")
}
Prints
WARNING: foo
Since Sequel just calls set_notice_receiver from PG, I guess I should file a bug report with PG.
EDIT 2
Yet when I try things just with the PG gem I get
conn = PG.connect( :dbname => 'db_test', user: 'test', password: 'test', host: '127.0.0.1' )
conn.set_notice_receiver{|r| puts r.result_error_message }
conn.exec("SELECT emit_notice()")
NOTICE: NOTICE ME!!!
=> #<PG::Result:0x0000000405ac18 status=PGRES_TUPLES_OK ntuples=1 nfields=1 cmd_tuples=1>
So at this point I'm a bit confused...
EDIT 3
Posted an issue GitHub...
EDIT 4
Ah, apparently there's another options you need to use, client_min_messages needs to be set to :notice as so:
DB = Sequel.connect(
ENV['DATABASE_URL'],
notice_receiver: proc{|r| puts r.result_error_message},
client_min_messages: :notice
)
and this works
You pass in your own proc which gets the notice as a string. To have it trigger on notices and not just warnings and above, use client_min_messages. For example:
a = nil
Sequel.connect(
DB.opts.merge(
notice_receiver: proc{|r| a = r.result_error_message},
client_min_messages: :notice)) { |db|
db.do("BEGIN\nRAISE WARNING 'foo';\nEND;")
}
a == "WARNING: foo\n" # true
I'm trying to deploy my sinatra on Heroku https://www.heroku.com/home
I was successful before I tried post method which gave me 404
Get methods work fine:
here is the example of the code:
get '/getPriceList' do //no error, everything works fine
content_type :json, charset: 'utf-8'
today_menu.to_json
end
post '/makeOrder', provides: :json do //error NOT FOUND
data = request.env['rack.input'].read
parsed_data = JSON.parse data.force_encoding('UTF-8')
if User.where(:name => parsed_data['userName']).first.nil?
current = Time.now
fixed = Time.local(current.year, current.month, current.day, 18, 40, 0)
if current > fixed
ObedResponse.new(data, false, 'Vi ne uspeli').to_json
else
#user = User.create(:name => parsed_data['userName'])
#some stuff
end
ObedResponse.new(data, true, "").to_json
end
else
ObedResponse.new(data, false, 'Сегодня вы уже заказали').to_json
end
Can someone tell me why I'm getting this error and how to make the thing work?
PS: I don't have this error while deploying locally using
bundle exec ruby obed.rb -e production
to start
I was in the wrong branch when I commited into Heroku. Changing the branch to master solved the issue.
I am trying to update test case of a particular scenario. But it saying that undefined method update for :test_case symbol.
Need help on this..
My updating method is....
def dataValidInput(featName,testCase)
fields = {:workspace => #rally["workspace"],
:project => #rally["project"],
:work_product => featName,
:test_case => testCase,
:validation_input => #step_name,
:name => testCase}
test_case = #slm.update(:test_case,fields)
end
Am getting output as...
undefined method `update' for :test_case:Symbol (NoMethodError)
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rally_rest_api-1.1.0/lib /rally_rest_api/rally_rest.rb:105:in `update'
C:/Users/CukesRally/features/CreateTC10.rb:176:in `nilValidInput'
C:/Users/CukesRally/features/CreateTC10.rb:154:in `chek_Steps'
C:/Users/CukesRally/features/CreateTC10.rb:132:in `find_or_create_test_case'
C:/Users/CukesRally/features/CreateTC10.rb:104:in `after_features'
C:/Users/CukesRally/features/CreateTC10.rb:93:in `before_test_case'
My Command :
cucumber C:/Users/CukesRally/features/Plan.feature --format MyTest::CreateStep
Thanks
First of all, I see that you're using an outdated gem. Please switch to using the rally_api gem. The latest version is 1.1.2: https://rubygems.org/gems/rally_api/versions/1.1.2
Then, if you still need help, please point me to a repo where the code is located or provide a gist link. I'd like to know where #slm and :work_product are defined as they seem to be the source of your error.
So, I am trying to get redmine_backlogs to work with SQL server. [We are using SQL Server rather than SQLite, to scale better]
I am NOT a Ruby programmer, but I really want this plugin for my team, as we actively use Redmine for several projects.
After reading through some Ruby tutorials, I've managed to get make some modifications and get the plugin installed and migrated correctly [it appears].
On the plugin settings screen [in administration] in Redmine, it shows the migration wasn't successful.
Even though all the list items are green, and the migrations appeared to work.
Any ideas?
The changes I made were to bypass suspected issues with the way Active records handles direct SQL queries.
Here are the changes I've made -
ERROR #1 –
C:\Projects\Redmine\redmine-2.3.2>rake redmine:plugins:migrate
Migrating redmine_backlogs (Redmine Backlogs)...
== AddStoryPositions: migrating ==============================================
-- execute("select max(position) from issues")
-> 0.0020s
-> -1 rows
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `each' for -1:FixnumC:/Projects/Redmine/redmine-2.3.2/plugins/redmine_backlogs/db/migrate/026_add_story_positions.rb:10:in `up'
FIX #1 –
Direct queries are not working correctly with the sqladapter [TinyTds + Active Record]
026_add_story_positions.rb
class AddStoryPositions < ActiveRecord::Migration
def self.up
# Rails doesn't support temp tables, mysql doesn't support update
# from same-table subselect
unless RbStory.trackers.size == 0
max = 0
dbconfig = YAML.load_file(File.join(File.dirname(__FILE__), '../../../../config/database.yml'))#[Rails.env]['username']
if dbconfig[Rails.env]['adapter'] == 'sqlserver' then
database = dbconfig[Rails.env]['database']
dataserver = dbconfig[Rails.env]['dataserver']
mode = dbconfig[Rails.env]['mode']
port = dbconfig[Rails.env]['port']
username = dbconfig[Rails.env]['username']
password = dbconfig[Rails.env]['password']
client = TinyTds::Client.new(
:database => database,
:dataserver => dataserver,
:mode => mode,
:port => port,
:username => username,
:password => password)
client.execute("select max(position) from issues").each{|row| max = row[0]}
client.execute "update issues
set position = #{max} + id
where position is null and tracker_id in (#{RbStory.trackers(:type=>:string)})"
else
execute("select max(position) from issues").each{|row| max = row[0]}
execute "update issues
set position = #{max} + id
where position is null and tracker_id in (#{RbStory.trackers(:type=>:string)})"
end
end
end
def self.down
puts "Reverting irreversible migration"
end
end
ERROR #2
rake aborted!
An error has occurred, this and all later migrations canceled:
TinyTds::Error: ALTER TABLE ALTER COLUMN position failed because one or more objects access this column.: ALTER TABLE [issues] ALTER COLUMN [position]
integer NOT NULLC:/Projects/Redmine/redmine-2.3.2/plugins/redmine_backlogs/db/migrate/033_unique_positions.rb:30:in `up'
FIX #2
033_unique_positions.rb
#SQLServer cannot change the type of an indexes column, so it must be dropped first
remove_index :issues, :position
change_column :issues, :position, :integer, :null => false
add_index :issues, :position
ERROR #3
rake aborted!
undefined method each' for -1:Fixnum
C:/Projects/Redmine/redmine-2.3.2/plugins/redmine_backlogs/lib/backlogs_setup.rb:155:inmigrated?'
FIX #3
def migrated?
available = Dir[File.join(File.dirname(__FILE__), '../db/migrate/*.rb')].collect{|m| Integer(File.basename(m).split('_')[0].gsub(/^0+/, ''))}.sort
return true if available.size == 0
available = available[-1]
ran = []
dbconfig = YAML.load_file(File.join(File.dirname(__FILE__), '../../../config/database.yml'))#[Rails.env]['username']
if dbconfig[Rails.env]['adapter'] == 'sqlserver' then
database = dbconfig[Rails.env]['database']
dataserver = dbconfig[Rails.env]['dataserver']
mode = dbconfig[Rails.env]['mode']
port = dbconfig[Rails.env]['port']
username = dbconfig[Rails.env]['username']
password = dbconfig[Rails.env]['password']
client = TinyTds::Client.new(
:database => database,
:dataserver => dataserver,
:mode => mode,
:port => port,
:username => username,
:password => password)
client.execute("select version from schema_migrations where version like '%-redmine_backlogs'").each{|m|
ran << Integer((m.is_a?(Hash) ? m.values : m)[0].split('-')[0])
}
else
Setting.connection.execute("select version from schema_migrations where version like '%-redmine_backlogs'").each{|m|
ran << Integer((m.is_a?(Hash) ? m.values : m)[0].split('-')[0])
}
end
return false if ran.size == 0
ran = ran.sort[-1]
return ran >= available
end
module_function :migrated?
I was using the wrong where clause -
This is the correct one, I must have overwritten when debugging.
'%-redmine_backlogs'
The above code works.
I could not answer my own question before, but now I can.
The above code was tested and works. I have been running backlogs on Windows with MS SQL successfully since.