Creating user from rails console command? - ruby-on-rails

I am newbie in Ruby, I am trying to install one app that says:
lobsters$ rails console
Loading development environment (Rails 4.1.8)
irb(main):001:0> User.create(:username => "test", :email => "test#example.com", :password => "test", :password_confirmation => "test", :is_admin => true, :is_moderator => true
irb(main):002:0> Tag.create(:tag => "test")
When I run rails console, it outputs "create some file" So how do I create user?

Try this :
User.create!(username: "test", email: "test#example.com", password: "test", password_confirmation: "test", is_admin: true, is_moderator: true)
In practice, Ruby programmers reserve ! to adorn the names of methods that do something unexpected, or perhaps a bit dangerous
So in this case, the "unexpected" result is that an exception is
raised instead of just failing and returning false.

Related

Rails 4 - nil value on rake db:seed [duplicate]

I have a CarrierWave rails uploader. I want to seed the database with fake users so I'm trying to add the images in with the same seed file. The images are in a common storage, so if I can just get the avatar strings in the database they'll work. When it saves the users though the image's aren't sticking.
# db/seeds.rb
user1 = User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => "v1357014344/bdylan.jpg"
user1.save
# IRB
User.first
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
> a = User.first
> a.avatar = "v1357014344/bdylan.jpg"
> a.save
(10.7ms) commit transaction
=> true
> a
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
You will have to insert the data in the following way.
File.open(File.join(Rails.root, 'test.jpg'))
So the entire user create would look like
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => open("v1357014344/bdylan.jpg")
Related question
Besides using open() as Nishant suggestions, you can also specify remote_avatar_url to manually set the remote URL.
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :remote_avatar_url => "http://upload.wikimedia.org/wikipedia/commons/2/28/Joan_Baez_Bob_Dylan_crop.jpg"
Thanks to JosephJaber for suggesting this in Seeding file uploads with CarrierWave, Rails 3
I used this approach to populate some video URLs for CarrierWave Uploader in my seeds.rb
To update the database directly and skip out on CarrierWave:
model[:attribute] = 'url.jpg'
model.save

Override Rails Uploader to seed database

I have a CarrierWave rails uploader. I want to seed the database with fake users so I'm trying to add the images in with the same seed file. The images are in a common storage, so if I can just get the avatar strings in the database they'll work. When it saves the users though the image's aren't sticking.
# db/seeds.rb
user1 = User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => "v1357014344/bdylan.jpg"
user1.save
# IRB
User.first
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
> a = User.first
> a.avatar = "v1357014344/bdylan.jpg"
> a.save
(10.7ms) commit transaction
=> true
> a
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
You will have to insert the data in the following way.
File.open(File.join(Rails.root, 'test.jpg'))
So the entire user create would look like
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => open("v1357014344/bdylan.jpg")
Related question
Besides using open() as Nishant suggestions, you can also specify remote_avatar_url to manually set the remote URL.
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :remote_avatar_url => "http://upload.wikimedia.org/wikipedia/commons/2/28/Joan_Baez_Bob_Dylan_crop.jpg"
Thanks to JosephJaber for suggesting this in Seeding file uploads with CarrierWave, Rails 3
I used this approach to populate some video URLs for CarrierWave Uploader in my seeds.rb
To update the database directly and skip out on CarrierWave:
model[:attribute] = 'url.jpg'
model.save

OmniAuth ActiveRecord error when pushing to Heroku

I'm having a strange situation occuring where I'm able to read and save information from a Facebook response via Omniauth when running locally, but when I push the exact code to Heroku the error below is coming up (from my logs) regarding the column first_name.
Processing by AdminController#index as HTML
Rendered admin/list_users.html.erb within layouts/application (60.9ms)
Completed 500 Internal Server Error in 163ms
ActionView::Template::Error (undefined method `first_name' for #<Aquarist:0x00000001ee8>):
: <td>Nickname: <%= aquarist.nickname %>
: 32: Last: <%= aquarist.last_name %></td>
: 29: <td><%= aquarist.name %></td>
: 31: First: <%= aquarist.first_name %>
: 34: <td><%= aquarist.email %></td>
: 28: <td><%= image_tag(aquarist.image, :width => '20') %></td>
: 33: <td><%= aquarist.provider %></td>
I'm using the term "aquarist" in place of user... I know this isn't standard use but for my use case it seems to make a bit more sense. I may change it back in time...
Here's my facebook callback from omniauth:
--- !ruby/hash:OmniAuth::AuthHash
provider: facebook
uid: '12456789'
info: !ruby/hash:OmniAuth::AuthHash::InfoHash
email: my#email.address.com
name: Alex
first_name: Alex
last_name: Lastname
image: http://graph.facebook.com/123456789/picture?type=square
urls: !ruby/hash:Hashie::Mash
Facebook: http://www.facebook.com/profile.php?id=12456789
credentials: !ruby/hash:Hashie::Mash
token: AACCCCb1i3ZALXEMfGxJtKZA
expires_at: 13378794564
expires: true
extra: !ruby/hash:Hashie::Mash
raw_info: !ruby/hash:Hashie::Mash
id: '12456789'
name: Alex Lastname
first_name: Alex
last_name: Lastname
link: http://www.facebook.com/profile.php?id=12456789
gender: male
email: my#email.address.com
timezone: 11
locale: en_US
verified: true
updated_time: '2012-02-01T12:51:00+0000'
As you can see I've locked down my facebook profile so don't expect to get all the extra information (eg relationship status etc).
I'm trying to build a basic profile of new users ("aquarists" in my terminology) which will pick up some of the extra information they are happy to share from facebook.
When I do this locally it works fine, I can collect my first_name, last_name, gender and locale for instance and save it to the database.
Here's the code I'm using to write the profile
def self.create_with_omniauth(auth)
create! do |aquarist|
aquarist.provider = auth["provider"]
aquarist.uid = auth["uid"]
aquarist.name = auth["info"]["name"]
aquarist.nickname = auth["info"]["nickname"]
aquarist.email = auth["info"]["email"]
aquarist.image = auth["info"]["image"]
aquarist.first_name = auth["extra"]["raw_info"]["first_name"]
aquarist.last_name = auth["extra"]["raw_info"]["last_name"]
aquarist.user_location = auth["extra"]["raw_info"]["user_location"]
aquarist.user_hometown = auth["extra"]["raw_info"]["user_hometown"]
aquarist.age = auth["extra"]["raw_info"]["age"]
aquarist.locale = auth["extra"]["raw_info"]["locale"]
aquarist.gender = auth["extra"]["raw_info"]["gender"]
end
end
I'm then using this code to display this profile information (in a table):
<% #aquarists.each do |aquarist|%>
<tr class="tbody">
<td><%= aquarist.uid %></td>
<td><%= image_tag(aquarist.image, :width => '20') %></td>
<td><%= aquarist.first_name %></td>
..and so on
The identical information when I push this code comes up with the active record error as per above.
If however I remove any of the columns from the [raw_info][extra] section the code works on Heroku (eg full name, UID, provider etc are all saved to the db).
The thing that has me completely confused is that this code is working locally - so I gather I'm requesting data from the "raw_info" section correctly.
I've already confirmed I've run my migrations on Heroku, and have - as some of other Q&As suggest - also used 'heroku restart' to ensure the database columns are being picked up in the app.
This is my OmniAuth entry in my gemfile:
gem 'omniauth'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
I'm running Rails 3.1.3 and postgres 9.1.2 locally. I'm using the free Heroku database which I believe runs PG 8.x.
Here's an extract from the migration file that creates the particular columns:
def change
add_column("aquarists", "first_name", :text, :default => "")
add_column("aquarists", "last_name", :text, :default => "")
add_column("aquarists", "gender", :text, :default => "")
add_column("aquarists", "user_location", :text, :default => "")
add_column("aquarists", "user_relationships", :text, :default => "")
add_column("aquarists", "user_hometown", :text, :default => "")
add_column("aquarists", "age", :integer)
add_column("aquarists", "locale", :text, :default => "")
add_column("aquarists", "image", :text, :default => "")
add_column("aquarists", "timezone", :text, :default => "")
add_column("aquarists", "last_login", :datetime)
end
And this is what comes back when I run heroku console:
$ heroku run console
Running console attached to terminal... up, run.1
Loading production environment (Rails 3.1.3)
irb(main):001:0> Aquarist.new
=> #<Aquarist id: nil, nickname: nil, name: nil, email: nil, created_at: nil, updated_at: nil, provider: nil, uid: nil, admin: false, age: nil, locale: "", image: "", timezone: "", last_login: nil, visits: nil>
irb(main):002:0>
Any views on what may be happening when my code is hitting Heroku? Is it a Postgres version issue?
Worked out what it was ... a botched migration file. Somewhere along the line I made a (silly) modification to an original migration file, and ran it correctly in my development environment but forgot to reverse the change online.
Won't do that again, I could do with the 8 or so hours back in my life. :)

Why is this RSpec test failing?

I'm in the process of learning Ruby on Rails, so treat me like a total neophyte, because I am.
I've got a User model with some associated RSpec tests, and the following test fails:
require 'spec_helper'
describe User do
it 'should require a password' do
User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''}).should_not be_valid
end
end
The relevant part of the User model looks like this:
class User < ActiveRecord::Base
...
validates :password, :presence => true,
:confirmation => true,
:length => { :minimum => 6 }
...
end
Here's the catch: if I run User.new(...).valid? from a Rails console using the arguments above, it returns false as expected and shows the correct errors (password is blank).
I was using spork/autotest and I restarted both to no avail, but this test also fails even running it directly with rspec. What am I doing wrong here?
EDIT
I tried a few more things with the test. This fails:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.should_not be_valid
So does this:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.valid?
u.errors.should_not be_empty
This passes, confirming that :password is indeed blank:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.password.should == ''
So, it's actually spork that is causing the problem. You can turn caching off, so that it won't need restarting every time :
http://ablogaboutcode.com/2011/05/09/spork-testing-tip-caching-classes
I think this is what happens :
ruby-1.9.2-p180 :020 > u = User.new
=> #<User id: nil, email: ...
ruby-1.9.2-p180 :021 > u.errors
=> {}
ruby-1.9.2-p180 :022 > u.save
=> false
ruby-1.9.2-p180 :023 > u.errors
=> {:email=>["can't be blank", "can't be blank"], ...}
In short, if you change new to create, it will work :) I think that this happens because the matcher be_valid checks on the model validation errors. There can be a deeper explanation, but i think that if you use create instead of new, it will work.
EDIT : I have a be_valid_verbose version that might help. Just create a 'be_valid_verbose.rb' file in your rspec/custom_matchers folder, and inside it write :
RSpec::Matchers.define :be_valid_verbose do
match do |model|
model.valid?
end
failure_message_for_should do |model|
"#{model.class} expected to be valid but had errors:n #{model.errors.full_messages.join("n ")}"
end
failure_message_for_should_not do |model|
"#{model.class} expected to have errors, but it did not"
end
description do
"be valid"
end
end
Now check against be_valid_verbose instead of be_valid. It will hopefully present you with some more information on what is happening in your case.
As I feared, the answer was stupidity. This was a spork problem. I thought I had killed the existing process and was running rspec independently, but I later found the spork process still running in a different shell, and rspec had been connecting to it all along. Restarting spork (or killing it entirely) and re-running the tests fixed the problem.
I found this particularly deceptive in that rspec continually updated the test output to reflect the fact that it was aware of my test changes, so it appeared to me that it was running against up-to-date code. Now I'm left to wonder what the real utility of spork is, since apparently I can't trust that it's actually running the right tests correctly.

Create a devise user from Ruby console

Any idea on how to create and save a new User object with devise from the ruby console?
When I tried to save it, I'm getting always false. I guess I'm missing something but I'm unable to find any related info.
You can add false to the save method to skip the validations if you want.
User.new({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" }).save(false)
Otherwise I'd do this
User.create!({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" })
If you have confirmable module enabled for devise, make sure you are setting the confirmed_at value to something like Time.now while creating.
You should be able to do this using
u = User.new(:email => "user#name.com", :password => 'password', :password_confirmation => 'password')
u.save
if this returns false, you can call
u.errors
to see what's gone wrong.
When on your model has :confirmable option this mean the object user should be confirm first. You can do two ways to save user.
a. first is skip confirmation:
newuser = User.new({email: 'superadmin1#testing.com', password: 'password', password_confirmation: 'password'})
newuser.skip_confirmation!
newuser.save
b. or use confirm! :
newuser = User.new({email: 'superadmin2#testing.com', password: 'password', password_confirmation: 'password'})
newuser.confirm!
newuser.save
If you want to avoid sending confirmation emails, the best choice is:
u = User.new({
email: 'demo#greenant.com.br',
password: '12feijaocomarroz',
password_confirmation: '12feijaocomarroz'
})
u.confirm
u.save
So if you're using a fake email or have no internet connection, that'll avoid errors.
None of the above answers worked for me.
This is what I did:
User.create(email: "a#a.com", password: "asdasd", password_confirmation: "asdasd")
Keep in mind that the password must be bigger than 6 characters.

Resources