Rails: test module and model conflict - ruby-on-rails

It was a mistake, but I called some model Test (cause it actually a test). Now it is really late to rollback it and give model another name, because this way I need to check a lot of code on changing model name.
Problem. When I call anything about Test in console, it causes error.
>> User.last
#<User id: 44, email: nil, password_digest: nil, created_at: "2013-05-08 11:26:04", updated_at: "2013-05-08 11:26:04", guest: true>
User Load (4.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
>> #test=Test.last
NoMethodError: undefined method `last' for Test:Module
from (irb):7
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
from C:/Users/HP/study/script/rails:6:in `require'
from C:/Users/HP/study/script/rails:6:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
What can I do?

You can rename the model, rails g migration rename_test. Then edit the migration like so
class RenameTest < ActiveRecord::Migration
def self.up
rename_table :test, :my_test
end
def self.down
rename_table :my_test, :test
end
end

Related

RUBY - Couldn't find User with 'id'=1

I am currently receiving this error:
ActiveRecord::RecordNotFound in MainController#index
After I destroyed a preference, which was held by myself.
Error:
ActiveRecord::RecordNotFound in MainController#index
Couldn't find User with 'id'=1
def get_owner
return User.find( self.owner ); // LINE WITH ERROR
end
Here is post.rb:
class Post < ActiveRecord::Base
enum status: [ :ps_normal, :ps_locked, :ps_blocked, :ps_protected ]
enum sortable: [ :school, :company, :date ]
validates :owner, presence: true
def owner_name
return self.get_owner.display_name;
end
def get_owner
return User.find( self.owner );
end
def readable?
return (self.status != :blocked ) ? true : false;
end
end
UPDATE#1
2.3.0 :001 > User.find(1)
User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=1
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:324:in `raise_record_not_found_exception!'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:444:in `find_one'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:71:in `find'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/querying.rb:3:in `find'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/core.rb:131:in `find'
from (irb):1
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
How should I fix this? Add userid=1?
Update #2
I deleted my own preference under my own username and I received this error. People are saying I am missing id=1, but I am unsure on how to add it back into the database
As per your console output, there is no user with the id of 1. So if you need a user with id=1 you can do it like this.
First, create a user with the same details which you had for the deleted user. After the user successfully created then go to Rails console and:
u = User.last
# => #<User id: x, ...... >
u.update_column(:id, 1)
Please refer to Rails API doc here for more info. Choose according to the Rails version that you are using.

Unable to query hstore attribute in Rails [duplicate]

This question already has answers here:
NoMethodError when I try to acces a field of an object taken from the DB
(4 answers)
Closed 7 years ago.
I've added a hstore attribute to my model:
class ChangePerDayAverageInterestToHstore < ActiveRecord::Migration
def change
add_column :companies, :per_day_average_interest, :hstore
end
end
Now when I generate the item via the console, I am able to query it without issue. Like so:
irb(main):002:0> t = Company.new per_day_average_interest: {1 => 10, 2 => 3}
irb(main):011:0> t.per_day_average_interest
=> {"1"=>"10", "2"=>"3"}
irb(main):013:0> t.per_day_average_interest["1"] => "10"
irb(main):014:0> t.per_day_average_interest["2"]
=> "3"
When I save it, then query it, I get a No Method error:
irb(main):028:0> t.save!
(0.2ms) BEGIN SQL (0.3ms) INSERT INTO "companies" ("created_at", "per_day_average_interest", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2015-06-08 19:24:39.694533"], ["per_day_average_interest", "\"1\"=>\"10\",\"2\"=>\"3\""], ["updated_at", "2015-06-08 19:24:39.694533"]]
(21.4ms) COMMIT
=> true
irb(main):029:0> d = Company.where(:id => 44)
Company Load (0.5ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 44
=> #<ActiveRecord::Relation [#<Company id: 44, name: nil, average: nil, created_at: "2015-06-08 19:24:39", updated_at: "2015-06-08 19:24:39", revenue_average: nil, country: nil, job: nil, model_name:
nil, average_daily_interest: nil, per_day_average_interest: {"1"=>"10", "2"=>"3"}>]>
irb(main):030:0> d.per_day_average_interest
NoMethodError: undefined method `per_day_average_interest' for #<Company::ActiveRecord_Relation:0x007fa16d296dd0>
from /home/action/.gem/ruby/2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:136:in `method_missing'
from /home/action/.gem/ruby/2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:99:in `method_missing'
from (irb):30
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:90:in `start'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:9:in `start'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:69:in `console'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Am I querying it the wrong way? Is there something I am missing?
Thanks!
The where statement returns the collection of objects and your column belongs to one object so you need to do the following
d = Company.where(:id => 44).first
As you can see d is ActiveRecord::Relation object, which is a wrapper of the all Company objects after filtering using where. The reader method per_day_average_interest is defined on the Company model instance, so you need to call as I have shown below.
d.first.per_day_average_interest
if you want all the values d.pluck(:per_day_average_interest).

ActiveRecord Postgres adapter generating invalid SQL WHERE clause: WHERE("fieldname")

ActiveRecord 4.1.1 is generating some peculiar SQL on save that postgres is choking on:
SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
PG::InvalidTextRepresentation: ERROR: invalid input syntax for type boolean: "uid"
I'm pretty sure that the "boolean" being referred to here is actually the WHERE() syntax which is expecting a boolean expression as an argument.
uid is defined as the primary key on my model (see below)... but why is it just saying WHERE('uid') when it's doing select_all (see stacktrace)? (and why is it doing select_all on save?)
Rails Console
p = Project.new(name: "test", description: "test", workflow_id: 1)
=> #<Project name: "test", description: "test", user_id: nil, uid: nil, created_at: nil, updated_at: nil, workflow_id: 1, active: nil>
irb(main):031:0> p.save
(1.9ms) BEGIN
Project Load (5.5ms) SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
PG::InvalidTextRepresentation: ERROR: invalid input syntax for type boolean: "uid"
LINE 1: SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
^
: SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
(1.7ms) ROLLBACK
ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type boolean: "uid"
LINE 1: SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
^
: SELECT "projects".* FROM "projects" WHERE ('uid') LIMIT 1
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:815:in `async_exec'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:815:in `block in exec_no_cache'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract_adapter.rb:373:in `block in log'
from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract_adapter.rb:367:in `log'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:815:in `exec_no_cache'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:137:in `exec_query'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:947:in `select'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:31:in `select_all'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/query_cache.rb:69:in `select_all'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/querying.rb:39:in `find_by_sql'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation.rb:603:in `exec_queries'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation.rb:487:in `load'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation.rb:231:in `to_a'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation/finder_methods.rb:451:in `find_take'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation/finder_methods.rb:98:in `take'
... 41 levels...
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:219:in `within_new_transaction'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/transactions.rb:208:in `transaction'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/transactions.rb:268:in `block in save'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/transactions.rb:283:in `rollback_active_record_state!'
from /app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.1/lib/active_record/transactions.rb:267:in `save'
from (irb):31
from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.1/lib/rails/commands/console.rb:90:in `start'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.1/lib/rails/commands/console.rb:9:in `start'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:69:in `console'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.1/lib/rails/commands.rb:17:in `<top (required)>'
from /app/bin/rails:4:in `require'
from /app/bin/rails:4:in `<main>
Model
class Project < ActiveRecord::Base
self.primary_key = "uid"
end
ActiveRecord mixin for generating IDs
module ActiveRecordUIDExtension
extend ActiveSupport::Concern
def generate_uid
return unless self.class.column_names.include?("uid")
self.id = SecureRandom.random_number(36**10).to_s(36)
while !self.class.find_by(:uid, self.id).nil? do
self.id = SecureRandom.random_number(36**10).to_s(36)
end
end
end
ActiveRecord::Base.send(:include, ActiveRecordUIDExtension)
ActiveRecord::Base.send(:before_create, :generate_uid)
Gemfile.lock
activerecord (4.1.1)
activemodel (= 4.1.1)
activesupport (= 4.1.1)
arel (~> 5.0.0)
Your mixin doesn't make any sense. This part right here is causing the bad SQL:
self.class.find_by(:uid, self.id)
That's producing invalid SQL because you're telling it to. find_by has a flexible interface so it has to do some parsing to see how you're calling it. When you say:
find_by(a, b)
the argument parsing probably assumes that you're trying to use this form:
find_by('some_sql_snippet', placeholder_valid)
as in this example from the docs:
find_by("published_at < ?", 2.weeks.ago)
Then it will probably to_s the first argument and scan it for placeholders. When you say:
find_by(:uid, self.id)
you'll end up with :uid.to_s and self.id will be ignored because there aren't placeholders in that string. That would explain why you're seeing where ('uid') in the SQL.
Fix your mixin to make sense:
self.class.find_by(:uid => self.id)
or better, switch to exists? to avoid building a whole model instance just to see if there's a row in the database:
self.class.where(:uid => self.id).exists?
self.class.exists?(:uid => self.id)

Fine for first user but error for third user?

I'm working with this tutorial: http://ruby.railstutorial.org/chapters/a-demo-app#top
I've followed all steps exactly, so that will show you all of my relevant code.
I got the application to work, for the first user. That said, I added three users to the application I made, and it won't work for the third user. I'm wondering what I did wrong in order for that error message to occur. Here's what I did:
Loading development environment (Rails 4.0.2)
2.0.0-p353 :001 > first_user = User.first
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, first: "John", last: "Palfrey", email: "jpalfrey#andover.edu", status: "Confused as to why he's on Claire's application.", created_at: "2013-12-21 18:53:17", updated_at: "2013-12-21 18:53:17">
2.0.0-p353 :002 > first_user.microposts
Micropost Load (1.2ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Micropost id: 1, content: "This is rather odd.", user_id: 1, created_at: "2013-12-21 18:56:58", updated_at: "2013-12-21 18:56:58">, #<Micropost id: 3, content: "I hope Claire can figure this out, for the sake of ...", user_id: 1, created_at: "2013-12-21 18:57:32", updated_at: "2013-12-21 18:57:32">]>
2.0.0-p353 :003 > third_user = User.third
NoMethodError: undefined method `third' for #<Class:0x007fac91453928>
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
from (irb):3
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Any thoughts as to why this is happening? If you want to see my gem file, my models, and such, just check the link I provided above!
Thanks in advance,
~Janie
There is no such method as .third, only .first and .last. You'll want to try User.find(3), which is looking up the users by their ID.
You'll find this useful - http://guides.rubyonrails.org/active_record_querying.html
There is no such method as User.third, you can use: User.find(3) where 3 is the id of the third user.
If you are not sure that the id of the third User is 3, then you can do:
User.take(3).last

Ruby on Rails Console Error

I am try on to insert a value via the Rails console into the database, but it's not working.
the first command is
u=users.create(:name=>"bob",:address=>"Dublin")
this is the output after I running the first command
u=Users.create(:name=>"Ben",:address=>"Dublin")
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `users` (`address`, `created_at`, `email`, `name`, `password`, `updated_at`) VALUES ('Dublin', '2012-04-16 23:15:48', NULL, 'Ben', NULL, '2012-04-16 23:15:48')
(9.1ms) COMMIT
=> #<Users id: 2, name: "Ben", password: nil, email: nil, address: "Dublin", created_at: "2012-04-16 23:15:48", updated_at: "2012-04-16 23:15:48">
this is the second command
t=tweets.create(:status=>"I am a tweet from bob",:user=>u)
NameError: undefined local variable or method `tweets' for main:Object
from (irb):4
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Assuming you have a Tweet model, you want
u = User.first
t = Tweet.create(:status => "I am a tweet from bob", :user => u)

Resources