RUBY - Couldn't find User with 'id'=1 - ruby-on-rails

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.

Related

"RecordNotFound: Couldn't find User with" in rails tutorial

I follow the [railstutorial][rails tutorial] try to setup a simple web site.
In this page, after inserting several records to the Users table, I use rails console, trying to find out some records. But all findings fail.
Could anyone help explain why it fails? Thanks very much
2.0.0-p247 :064 > User.all
User Load (0.3ms) SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, name: "Shijie", email: "shijiexu#yahoo.com", created_at: "2016-12-24 22:36:56", updated_at: "2016-12-24 22:36:56">, #<User id: 2, name: "chen jie", email: "chejie#yahoo.com", created_at: "2016-12-24 22:37:36", updated_at: "2016-12-24 22:37:36">, #<User id: 3, name: "Michael Hartl", email: "mmm#example.com", created_at: "2016-12-25 20:56:58", updated_at: "2016-12-25 21:21:38">]>
2.0.0-p247 :065 > User.find(name: "Shijie")
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", nil]]
ActiveRecord::RecordNotFound: Couldn't find User with 'id'={:name=>"Shijie"}
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.2.0/lib/active_record/core.rb:154:in `find'
from (irb):65
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'
2.0.0-p247 :066 > User.find(email: "mmm#example.com")
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", nil]]
ActiveRecord::RecordNotFound: Couldn't find User with 'id'={:email=>"mmm#example.com"}
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.2.0/lib/active_record/core.rb:154:in `find'
from (irb):66
from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
The user.rb is generated.
class User < ActiveRecord::Base
has_many :microposts
end
The rails in my version is Rails 4.2.0, though the rails in the tutorial is for v5+.
The find method will look for the record using the id column. So, in your case, it checks for the record with the id value of email: "mmm#example.com" which obviously doesn't exist.
If you want to find records by a column other than id, use find_by method and pass the column name and value as a hash.
User.find_by(email: "mmm#example.com")
For more, read the documentation of find_by

PublicActivity: Get All of User's Distinct Activities

I'm using the Public Activity gem to track user's comments. I would like to get fetch all unique user comments in a query. I tried doing the following:
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).all.select(:trackable_id).distinct
But I'm getting the error:
ArgumentError: wrong number of arguments(1 for 0)
from (irb):14:in `select'
from (irb):14
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:47:in `start'
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:8:in `start'
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Does anyone know how to extract of a user's unique activities based on trackable_id?
For reference, this is what my query results look like before I attempt to fetch the unique records:
I did following on Rails Console, see what i got
2.0.0p353 :020 > PublicActivity::Activity.where(id:1).class
=> ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity
2.0.0p353 :021 > PublicActivity::Activity.all.class
=> ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity
2.0.0p353 :022 > PublicActivity::Activity.where(id:1).all.class
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
W, [2014-09-06T01:47:09.341145 #8594] WARN -- : DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
PublicActivity::Activity Load (0.6ms) SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
D, [2014-09-06T01:47:09.343063 #8594] DEBUG -- : PublicActivity::Activity Load (0.6ms) SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
=> Array
2.0.0p353 :023 >
As you can see,u are performing select operation on an array, that's why u are get such error ArgumentError: wrong number of arguments(1 for 0)
try this instead,
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).select(:trackable_id).distinct
The answer was to run the following:
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).select("DISTINCT ON (trackable_id) *")

Getting ActiveRecord::RecordInvalid error with has_many through association; validation issue on join table

I have three associated models like these:
class Product < ActiveRecord::Base
belongs_to :user
has_many :descriptions, {
dependent: :destroy,
before_add: [:add_user_id_to_description, :validate_description]
}
has_many :documents, through: :descriptions
# ...
def validate_description(d)
unless d.valid?
d.errors[:user_id].each do |err|
self.errors.add(:base, "Doc error: #{err}")
end
end
end
end
class Document < ActiveRecord::Base
belongs_to :user
has_many :descriptions, {
dependent: :destroy,
before_add: [:add_user_id_to_description, :validate_description]
}
has_many :products, through: :descriptions
end
class Description < ActiveRecord::Base
belongs_to :user
belongs_to :product
belongs_to :document
end
When I do something like:
doc = user.documents.build
doc.update_attributes(:product_ids => [1,2])
And the description validation fails, then I get false and the appropriate errors on doc. This is exactly what I want.
However, if doc already exists, e.g.:
doc = user.documents.first
doc.update_attributes(:product_ids => [1,2])
And the description validation fails, then I get an ActiveRecord::RecordInvalid error.
I know exactly why this happens--the insert_record method from has_many_through_association.rb calls save! internally, which propagates the error. It exits early, skipping this call, for new records.
Is there some way I can set up my models to prevent this save!? Or am I forced to rescue from the error?
EDIT
I've tried the setup described by Carlos Drew below; I've also tried setting validates_associated :descriptions, and adding inverse_of: :whatever to the has_many :descriptions options hash. I also tried setting a before_validation callback on the Product and Document models, but apparently association callbacks get run first (?). Each attempt seemed to produce the exact same error message.
I'm pasting my error trace from the console below.
Document Load (1.8ms) SELECT "documents".* FROM "documents" WHERE "documents"."user_id" = 19 ORDER BY "documents"."id" DESC LIMIT 1
(1.0ms) BEGIN
Product Load (41.7ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT 1 [["id", 3640]]
Product Load (4.1ms) SELECT "products".* FROM "products" INNER JOIN "descriptions" ON "products"."id" = "descriptions"."product_id" WHERE "descriptions"."document_id" = 3552
User Load (7.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 19 LIMIT 1
Account Load (2.0ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."user_id" = 19 LIMIT 1
(0.9ms) SELECT COUNT(*) FROM "descriptions" WHERE "descriptions"."user_id" = 19
(1.2ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: User You have reached limit of 1
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/validations.rb:56:in `save!'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/attribute_methods/dirty.rb:33:in `save!'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:264:in `block in save!'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:313:in `block in with_transaction_returning_status'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:208:in `transaction'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:311:in `with_transaction_returning_status'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:264:in `save!'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/has_many_through_association.rb:85:in `save_through_record'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/has_many_through_association.rb:52:in `insert_record'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:496:in `block (2 levels) in concat_records'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:344:in `add_to_target'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:495:in `block in concat_records'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:493:in `each'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:493:in `concat_records'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:134:in `block in concat'
... 14 levels...
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/associations/builder/collection_association.rb:71:in `block in define_writers'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/attribute_assignment.rb:85:in `block in assign_attributes'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/attribute_assignment.rb:78:in `each'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/attribute_assignment.rb:78:in `assign_attributes'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/persistence.rb:216:in `block in update_attributes'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:313:in `block in with_transaction_returning_status'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:208:in `transaction'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/transactions.rb:311:in `with_transaction_returning_status'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.13/lib/active_record/persistence.rb:215:in `update_attributes'
from (irb):2
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /usr/local/rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
My intuition is that you are over-engineering the validation of the models with that before_add: :validate_description. Are you not served by standard Rails/ActiveRecord methods and conventions? Specifically, validates: true can be set for validation handling between associated models.
Still, there are some gotchas around association validations, and I would recommend reading the following:
has_many association validations on new vs. existing records
validates_associated
Thoughtbot article on :inverse_of wrt to association validations (I don't think this is necessarily relevant to your setup)
EDIT
I got super curious about this and went and replicated the problem, as you described it, via specs (and it's in a public github project). I still think the manual before_add validations are overengineered and I didn't use them, but I am encountering the issue you describe.
So, what I'm trying to understand is whether what you're encountering is expected and desired. Rails is nothing if not opinionated, and maybe using direct setting of has_many-through associations is a sort of coder-beware use case. To be clear, what you're doing is a slightly weird thing: when you ask to set document.product_ids, what you're actually doing is setting matching document_id and product_id on certain description objects. Right? That's weird, and super unclear in intent/expected result.
What's an alternate approach, then? What you're doing is adding descriptions to a document, and those descriptions are on products. Why not, then, interact with the document products through the description interface? That should avoid the has_many-through setter weirdness, and provider a clearer, interface, I think.

Rails: test module and model conflict

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

'name' AR attribute returning class name and id not working

I have a User object and getting name like this is fine:
>u=User.find(1)
>u.name
>jt
but it has an association with an object that when I get the user back it returns the name of the class:
oc=ObjectConnection.find(1)
oc.user.name
> User
and the id is giving me an error:
ruby-1.9.2-p290 :063 > oc.user.id
NoMethodError: User Load (0.4ms) SELECT id, name FROM `users` WHERE (id=1)
undefined method `id' for [#<User id: 1, name: "jt">]:ActiveRecord::Relation
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/relation.rb:459:in `method_missing'
from (irb):63
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
ruby-1.9.2-p290 :064 >
The classes are:
class ObjectConnection < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :object_connections
end
What is going on? This seems really simple.
thx
I have a nearly identical relationship between Contact and Company (Contact belongs_to company, company has_many contacts.) Here's my rails console (Rails 3.2, Ruby 1.9.3).
1.9.3p125 :019 > company = Company.find(1)
Company Load (2.7ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 1]]
=> #<Company id: 1, name: "Acme Corp", created_at: "2012-03-20 17:49:44", updated_at: "2012-03-20 17:49:44">
1.9.3p125 :020 > contact = Contact.find(1)
Contact Load (1.8ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = $1 LIMIT 1 [["id", 1]]
=> #<Contact id: 1, first: "Tom", last: "Harrison", email: "foo#example.com", created_at: "2012-03-12 19:11:57", updated_at: "2012-03-20 17:56:37", birthdate: "1962-02-26", company_id: 1>
1.9.3p125 :021 > contact.company.name
Company Load (0.7ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 1 LIMIT 1
=> "Acme Corp"
Perhaps there's some case where "name" was used in an earlier version of AREL? Also, notice the odd SQL syntax ... WHERE (id=1) ... What happens if you look for a different attribute of ObjectConnection?
This is an identical situation, isn't it? Perhaps the version of Rails? Ruby? Seems implausible, but the answer is "You're doing it right".

Resources