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)
Related
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
Following are 2 outputs from rails console:
1. Success
irb(main):038:0> Category.all
Category Load (0.0ms) SELECT "categories".* FROM "categories"
=> #<ActiveRecord::Relation [#<Category id: 1, name: "tutorials", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">, #<Category id: 2, name: "news", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">, #<Category id: 3, name: "design", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">]>
2. Failure
irb(main):039:0> Category.find(:all)
Category Load (0.0ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT 1 [["id", nil]]
ActiveRecord::RecordNotFound: Couldn't find Category with 'id'=all
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:324:in `raise_record_not_found_exception!'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:444:in `find_one'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:71:in `find'
from h:in `find'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/core.rb:130:in `find'
from (irb):39
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/console.rb:110:in `start'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/console.rb:9:in `start'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:68:in `console'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
irb(main):040:0>
The find(:all) syntax was removed in Rails 4. You can use Category.all to get the same result.
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).
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
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