add_index :name, :email:, unique: true not working for me - ruby-on-rails-4

I seen this question before on here but the solution on there is not working for me. Rake Aborted , on add_index(:users, :email, {:unique=>true})
In the Rails Tutorial by Michael Hartl he wants you to add_index :name, :email, unique: true I keep getting this error message.
$ bin/rake db:migrate RAILS_ENV=test
DL is deprecated, please use Fiddle
== 20141224060705 AddIndexToUsers: migrating ==================================
-- add_index(:users, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: indexed columns are not unique: CREATE UNIQUE INDE
X "index_users_on_email" ON "users" ("email")c:/Sites/example/db/migrate/2014122
4060705_add_index_to_users.rb:3:in `change'
c:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
there are no users in the database. here is a picture of the database

You have to enclose the attributes you want to add the index into an array like so:
add_index :users, [:name, :email], unique: true
The first argument is the table name, the second can be an array of attributes or a single attribute, and then some options.
Hope this helps!

Related

NoMethodError name RoR user.name

Followed the tutorial at SitePoint
for a simple sorcery app. I am receiving undefined method `name' for nil:NilClass
migration
class SorceryCore < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email, :null => false
t.string :crypted_password
t.string :salt
t.timestamps :null => false
end
add_index :users, :email, unique: true
end
end
/home/david/Magical/app/views/user_mailer/activation_needed_email.html.erb
<p>Welcome, <%= #user.name %>!</p>
<p>To login to the site, just follow <%= link_to 'this link',
activate_user_url$
<p>Thanks for joining and have a great day!</p>
users.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
validates :password, length: { minimum: 3 }
validates :password, confirmation: true
validates :email, uniqueness: true, email_format: { message: 'has
invalid format'
End
I took the long way home and cloned the Github repo. At first I was getting a 'stack level too deep' error, but I found that the gemfile loaded rails 4.2.1 .
I changed this to 4.2.10 and all went well after the migrations and minor tweaks in the tutorial.
along the way, I found rails_db gem which is a great simple gem for working with sqLite. rails_db gem

RSpec Model Testing: Failures

I am teaching myself RSpec (v3.1.7). I have installed rspec with rails g rspec:install into an existing rails app - freshly created.
I created a model: rails g rspec:model zombie. Ran the migration and all went well.
In: app/models/zombie.rb:
class Zombie < ActiveRecord::Base
validates :name, presence: true
end
In: app/spec/models/zombie_spec.rb:
require 'rails_helper'
RSpec.describe Zombie, :type => :model do
it 'is invalid without a name' do
zombie = Zombie.new
zombie.should_not be_valid
end
end
In terminal when I ran (in the app dir): rspec spec/models I get:
F
Failures:
1) Zombie is invalid without a name
Failure/Error: zombie.should_not be_valid
NoMethodError:
undefined method `name' for #<Zombie id: nil, created_at: nil, updated_at: nil>
# ./spec/models/zombie_spec.rb:6:in `block (2 levels) in <top (required)>'
Im following a video tutorial and I followed the video (Testing with RSpec) down to the latter. I'm like losing weight on the 2nd chapter. Am I missing something? Is the video using an older version of rspec for their video tutorial?
In my migration file:
class CreateZombies < ActiveRecord::Migration
def change
create_table :zombies do |t|
t.timestamps
end
end
end
Your model don't know what name is since you did not define the attribute in your migration:
class CreateZombies < ActiveRecord::Migration
def change
create_table :zombies do |t|
t.string :name
t.timestamps
end
end
end
Then run:
rake db:migrate
Then this should work fine:
z = Zombie.new(name: 'foo')
z.name
=> 'foo'
I think you are missing the name attribute. The following migration file will add name attribute to zombie model:
class AddNameToZombies < ActiveRecord::Migration
def change
add_column :zombies, :name, :string
end
end
finally run the following commands:
rake db:migrate
rake db:test:prepare
and that's it

Rails tutorial: undefined method

I'm stuck (again!) at Chapter 9 (this time in section 9.2.2) of the Rails tutorial. I am getting
bundle exec rspec spec/
................................FFF........................
Failures:
1) Authentication authorization as wrong user submitting a GET request to the Users#edit action
Failure/Error: before {sign_in user, no_capybara: true}
NoMethodError:
undefined method `new_remember_token' for #<User:0x007f8181815448>
# ./spec/support/utilities.rb:13:in `sign_in'
# ./spec/requests/authentication_pages_spec.rb:71:in `block (4 levels) in <top (required)>'
The other 2 errors are of the same type.
Here is spec causing the errors:
describe "as wrong user" do
let(:user) {FactoryGirl.create(:user)}
let(:wrong_user) {FactoryGirl.create(:user, email: "wrong#example.com")}
before {sign_in user, no_capybara: true}
describe "submitting a GET request to the Users#edit action" do
before {get edit_user_path(wrong_user)}
specify { expect(response.body).not_to match(full_title('Edit user'))}
specify { expect(response).to redirect_to(root_url)}
end
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user)}
specify { expect(response).to redirect_to(root_url)}
end
end
And here is the method (utilities.rb) the error message is complaining about:
def sign_in (user, options={})
if options[:no_capybara]
# Sign in when not using Capybara
remember_token = User.new_remember_token
cookies[:remember_token]
user.update_attribute(:remember_token, User.digest(remember_token))
else
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
end
The code for the model (User.rb) is here:
class User < ActiveRecord::Base
before_save { self.email = email.downcase}
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: {minimum: 6}
has_secure_password
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
I had previously trouble with the sign_in method but it miraculously disappeared. What am I doing wrong?
I finally found the culprit for the erratic test results that I have been observing in this case and, quite likely, on previous occasions (Failure/Error: sign_in user undefined method `sign_in', Rails named route not recognized). The problem seems to be that rails does not clear by default the cache between tests. Which is, actually, downright scary. It seems you cannot really trust the test results. I realised this by commenting out the method that rails was complaining about and re-running the test. The error persisted which meant one thing - rspec was simply working with some cached versions of the files and thus disregarding the changes which I am making. So even if the tests pass you can't be sure that they really do. This is really bizarre. After realising the problem with a bit of googling I found how to force rails to clean the cache - check jaustin's answer here: is Rails.cache purged between tests?

RubyMine Rails console create error

I'm currently working on a Ruby on Rails application using RubyMine 5.4.3.2.1. I'm using Rails 4 and Ruby 1.9.3p429. In my application, I have a class file 'user.rb' with the following code:
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness:{case_sensitive: false }
validates :password, length: { minimum: 6}
has_secure_password
before_save { self.email = email.downcase }
end
and a related migration file '[timestamp]_create_users.rb' with the following:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.timestamps
end
end
end
Using the RubyMines Run Rake Task, I ran a db:migration to create the users table. The problem is that RubyMines doesn't accept any User.create command to enter data into the database. E.g
User.create (first_name:"John",last_name:"Doe",email:"jdoe#example.com",password:"testing",password_confirmation:"testing")
The error it gives is
SyntaxError: (irb):1: syntax error, unexpected tLABEL
User.create (first_name:"John",last_name:"Doe",ema...
^
(irb):1: syntax error, unexpected ',', expecting $end
...er.create (first_name:"John",last_name:"Doe",email:"jdoe#...
^
This works fine when I run it in my command prompt using the 'rails console', but it gets tedious to repeatedly refer to the command prompt. I've tried running the Rails Console in RubyMine in both default and development, with neither yielding a positive result. Can anyone tell me what I'm doing wrong and how to resolve this?
remove the space between User.create and the left parenthesis User.create(...) instead of User.create (...)
Cheers

rails 4 has_many association bug?

i have an simple setup for a has_many association:
def Account
has_many :timers
end
def Timer
belongs_to :timer
end
if i try to build a timer i get this false behavior:
account.id => 1
account.timers.build => #<Timer id: nil, account_id: 0>
...of course it should be:
account.id => 1
account.timers.build => #<Timer id: nil, account_id: 1>
Because it's rails4 in tried the same with a fresh setup. and it works!
gems: pg, haml-rails, devise, simple_form, globalize3
Question: what could be the cause of breaking the Rails API ?
and the winner is:
gem 'globalize3', github: 'harlock/globalize3', branch: 'rails4-wip'