I am working through the Hartl tutorial and I have run into a problem. When I attempt to add a user in the console it doesn't return that it has saved any of the information I just entered. The code is below, hopefully you guys can steer me in the right direction.
The User model:
class User < ActiveRecord::Base
attr_accessor :name, :email
before_save { self.email = email.downcase}
validates :name, presence: true, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: {maximum: 255},
format: { with: VALID_EMAIL_REGEX },
uniqueness: {case_sensitive: false}
has_secure_password
validates :password, length: { minimum: 6 }
end
the error:
2.2.0 :003 > User.create(name: "Jim Bob", email: "jim#bob.com", password: "jimmybob", password_confirmation: "jimmybob")
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('jim#bob.com') LIMIT 1
SQL (0.4ms) INSERT INTO "users" ("password_digest", "created_at", "updated_at") VALUES (?, ?, ?) [["password_digest", "$2a$10$I61hwA3iAQmzsT/wbb0wpOSannOBNPLtQsBhscjakS5OgCi6zJoMq"], ["created_at", "2015-02-13 23:45:32.636129"], ["updated_at", "2015-02-13 23:45:32.636129"]]
(137.3ms) commit transaction
=> #<User id: 1, name: nil, email: nil, created_at: "2015-02-13 23:45:32", updated_at: "2015-02-13 23:45:32", password_digest: "$2a$10$I61hwA3iAQmzsT/wbb0wpOSannOBNPLtQsBhscjakS5...">
I don't understand why the name and the email will not save. Please any help would be amazing.
Its because you have defined attr_accessor for name and email.
attr_accessor will overwrite the methods generated by active records so its not been saved to database.
Related
I have problem with bulk inserts with RoR, using bulk_insert gem.
I have following code
User.bulk_insert(:username, :email, :password) do |worker|
100000.times do
worker.add username: 'aadsad', email: 'some#email', password: 'some password'
end
end
and everyting works properly.
The problem occurrs when i want to insert data with has_one relationship.
How can i insert relationship data to created entry ?
I try:
User.bulk_insert(:username, :email, :password, user_detail_attributes: [:firstname, :last_name, :phone, :city]) do |worker|
100000.times do
worker.add username: 'aadsad', email: 'some#email', password: 'some password', firstname: 'firstname', lastname: 'lastname', phone: '41', city: 'city'
end
end
but no effect, I receive error:
ArgumentError: unknown keyword: user_detail_attributes
Having a problem while creating a new record in database.
Model currently looks like this:
class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
before_save {!self.email.downcase}
validates :name, presence: true, length: {maximum: 50}
validates :email, presence: true, length: {maximum: 255}, format: {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false}
has_secure_password
validates :password, presence: true, length: {minimum: 6}
end
Initially tried to create a record from the code, but failed without any errors.
As a next step I tried to create a record manually in console, but still with the same result. No errors available. Skipping validations, reseting database, restarting server or excluding email REGEXP (always a source of troubles for me) from validations doesn't help...
user = User.new(name: "Fedor U", email: "fredy#mail.ru", password: "asdzxc123", password_confirmation: "asdzxc123")
=> #<User id: nil, name: "Fedor U", email: "fredy#mail.ru", created_at: nil, updated_at: nil, password_digest: "$2a$10$89SABxu2lOo3gj6DiqLZEOlSheAfEk0ex.5GYmJ5e8i...">
>> user.save
(0.2ms) begin transaction
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('fredy#mail.ru') LIMIT 1
(0.1ms) rollback transaction
=> false
>> user.errors.any?
=> false
user.errors.full_messages
=> []
>> user.save(validation: false)
(0.1ms) begin transaction
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('fredy#mail.ru') LIMIT 1
(0.1ms) rollback transaction
=> false
Any ideas what am I doing wrong? Rails 4.2.0, bcrypt 3.1.7. Database is empty at the moment.
!self.email.downcase will return true or false
use self.email.downcase! to change the email into smallcase.
I am new with ruby on rails and I am following Ruby on Rails 3 Essential Training 2010 from Lynda.
I have a problem with creating records in rails console even though I create the subject it returns nil. This is the code from the console:
vane#vane-HP-G70-Notebook-PC:~/Sites/simple_cms$ rails c
Loading development environment (Rails 3.2.8)
1.9.3-p194 :001 > subject = Subject.new(:name => "Fourth Subject", :position => 4, :visible => true)
=> Subject id: nil, name: nil, position: nil, visible: false, created_at: nil, updated_at: nil>
1.9.3-p194 :002 > subject.save
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO subjects (created_at, name, position, updated_at, visible) VALUES ('2012-10-10 15:06:11', NULL, NULL, '2012-10-10 15:06:11', 0)
(56.4ms) COMMIT
=> true
It doesn't show any error so I don't now what to do. Any help will be appreciated.
This is what i have in app>models subject.rb:
class Subject < ActiveRecord::Base
attr_accessor :name, :position, :visible
attr_accessible :name, :position, :visible
end
You probably need to make your attributes accessible so they can be assigned in your new call.
After i removed this line
attr_accessor :name, :position, :visible
from subject.rb the problem got solved.
I tried using Devise but since that didn't work out for me, I decided to build the authentication and sessions from scratch. I realize the problem wasn't devise, but it's mysql. For some reason, when I register a user, the information and attributes are stored in the database. When I login using the email and password, it keeps telling me that it's an invalid email/password. The log looks like this:
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NFudGruZS79uwDrKzbHDQrBjlcwQ7AkC958vI4aHDAs=", "session"=>{"email"=>"first#abc.com", "password"=>"[FILTERED]"}, "commit"=>"Sign in"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`email` IS NULL LIMIT 1
After some investigation, I know it's not because I didn't install mysql or other gems properly because a brand new app works just fine.
Does anyone know why it's not pulling the email I entered and pulling email is NULL instead?
Should I just create a new database and switch my database.yml file to the new database instead?
Thanks in advance.
EDIT - SOME MORE CODE
user model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :secondary_email, :password, :password_confirmation, :gender
has_many :user_owner_relationships
has_many :owners, :through => :user_owner_relationships
has_many :cash_endowments
has_many :checks, :through => :cash_endowments
has_many :owners, :through => :cash_endowments
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:uniqueness => { :case_sensitive => false },
:format => { :with => email_regex }
validates :name, :presence => true,
:length => { :maximum => 40 }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..20 }
sessions_controller (user controller is standard)
def new
#title = "Sign in"
end
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_path, :notice => "Welcome '#{user.first_name}"
else
flash.now.alert = "Invalid email or password."
render "new"
end
end
Rookie mistake -
It's actually because my new.html.erb for the sessions controller was not pulling the :session symbol from this code:
<%= form_for (:session, :url => sessions_path) do |f| %>
So I just ended up using form_tag instead.
I have created this migration in Rails:
class AddSocialSecurityNumberToContactTable < ActiveRecord::Migration
def self.up
add_column :contacts, :ss_number, :string
end
def self.down
remove_column :contacts, :ss_number
end
end
In my development database, which is a SQLite3 database, all the old Contact records gained the ss_number field, just nil. However, whenever I deploy the code with migrations, the old, pre-migration Contact records do not have a ss_number field. I have restarted the server and logged into the console and verified it both ways on both a production database (MySQL) and a staging database (MySQL).
If, however, I create a new record in the console, it does show a ss_number field for the Contact object.
>> a = Contact.find(1)
=> #<Contact id: 1, first_name: "Gary", last_name: "Simpson", email: "", home_phone: "", work_phone: "", mobile_phone: "", mailing_street: "123 Main St", mailing_street_2: "", mailing_city: "Little Rock", mailing_state: "AR", mailing_zip: "72205", created_by: 1, created_at: "2010-07-24 19:30:10", updated_at: "2010-07-24 19:30:10">
>> a.ss_number
ActiveRecord::MissingAttributeError: missing attribute: ss_number
from /srv/www/domain/releases/20100727004056/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:217:in `send'
from /srv/www/domain/releases/20100727004056/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:217:in `method_missing'
from (irb):4
>> a = Contact.new
=> #<Contact id: nil, first_name: nil, last_name: nil, email: nil, home_phone: nil, work_phone: nil, mobile_phone: nil, mailing_street: nil, mailing_street_2: nil, mailing_city: nil, mailing_state: nil, mailing_zip: nil, created_by: nil, created_at: nil, updated_at: nil, ss_number: nil>
>> a.ss_number
=> nil
How can I make it so that all existing Contact rows have nil as their value after I migrate?
You can add Find statments and blocks to your migration code, so you could do something like this:
def self.up
add_column :contacts, :ss_number, :string
Contacts.find(:all).each do |contact|
contact.ss_number = nil
contact.save
end
end
Hope this helps!
Alternatively, I believe you could just do this:
add_column :contacts, :ss_number, :string, :null=>true
The
:null=>true
at the end will set it as the default as it adds the column to the table.