NoMethodError name RoR user.name - ruby-on-rails-4

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

Related

add_index :name, :email:, unique: true not working for me

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!

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

Rgeo, Mysql and Spatial index error

when trying to run migration to add a spatial index, get
Unknown key: spatial/Users/ME/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.2/lib/active_support/core_ext/hash/keys.rb:70:in `block in assert_valid_keys'
Using
Ruby 2.0.353
Rails 4.0.2
RGEO 0.3.20
RGEO Active Record 0.4.6
List item
activerecord-mysql2spatial-adapter 0.4.3
Migration Index file looks like
class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses, :options => 'ENGINE=MyISAM' do |t|
t.string :street_1
t.string :street2
t.string :city
t.string :state
t.string :zip
t.string :country
t.string :full_address
t.column :latlon, :point, :null => false
t.timestamps
end
add_index :addresses, :latlon, :spatial => true
end
end
UPDATE
Corrected this and other errors when I changed the adapter in my database.yml file from mysql2 to mysql2spatial

Mongoid Model won't persist has_one via embeds_one relation

I'm having trouble with embeds in a mongoid4-based rails 4 app. I've been looking for an answer everywhere for the past 2 days. So here is the code.
This is a church management app, with a Service model, embedding a team and a band. Each team/band has several roles such as "presidence", "communion" that refer to a user.
My models :
class Service
include Mongoid::Document
...
embeds_one :team, autobuild: true
embeds_one :band, autobuild: true
...
accepts_nested_attributes_for :team, :band
end
class Team
include Mongoid::Document
embedded_in :service
has_one :presidence, :class_name => 'User', autosave: true
has_one :message, :class_name => 'User', autosave: true
...
end
class Band
include Mongoid::Document
has_one :lead, :class_name => 'User', autosave: true
has_one :guitar, :class_name => 'User', autosave: true
...
embedded_in :service
end
class User
include Mongoid::Document
embeds_one :profile
belongs_to :team, :inverse_of => :presidence
belongs_to :team, :inverse_of => :message
belongs_to :band, :inverse_of => :lead
belongs_to :band, :inverse_of => :guitar
def fullname
"#{profile.firstname} #{profile.lastname}"
end
def self.find_by_talent(talent)
self.where("profile.talents.name" => talent)
end
end
The services controller :
# POST /services
# POST /services.json
def create
#service = Service.new(service_params)
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render action: 'show', status: :created, location: #service }
else
format.html { render action: 'new' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
...
def service_params
params.require(:service).permit(:date, :time, :place, :name, :theme, :team => [:id, :precedence, :message ], :band => [:id, :lead, :guitar ])
end
And the form in _form.html.erb :
<%= form_for(#service) do |f| %>
...
<%= f.fields_for #service.team do |tf| %>
<%= tf.collection_select :presidence, User.find_by_talent(:presidence), :_id, :fullname, {:include_blank => "select a person"} %>
<%= tf.collection_select :message, User.find_by_talent(:message), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
<%= f.fields_for #service.band do |bf| %>
<%= bf.collection_select :lead, User.find_by_talent(:lead), :id, :fullname, {:include_blank => "select a person"} %>
<%= bf.collection_select :guitar, User.find_by_talent(:guitar), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
...
<% end %>
When creating a service, everything seems to run fine, but this is what I get in the console :
2.0.0-p195 :001 > s = Service.last
=> #<Service _id: 52ea18834d61631e7e020000, date: "2014-02-02", time: "10:00", place: "Where it's at", name: "My great name", theme: "The service's theme">
2.0.0-p195 :002 > s.team
=> #<Team _id: 52ea18834d61631e7e030000, >
2.0.0-p195 :003 > s.team.presidence
=> nil
Why is s.team.presidence not created ? s.team looks weird, too, with an ending comma...
Here is the content of my rails log :
Started POST "/services" for 127.0.0.1 at 2014-01-30 10:16:51 +0100
Processing by ServicesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ph6lbdHC2FbiANn/fGSzHWprenj3fWKXM40Hrsc5+AM=", "service"=>{"date"=>"2014-02-02", "name"=>"My great name", "theme"=>"The service's theme", "time"=>"10:00", "place"=>"Where it's at", "team"=>{"presidence"=>"52ea18324d61631e81010000", "message"=>"52ea18324d61631e81010000"}, "band"=>{"lead"=>"52ea18324d61631e81010000", "guitar"=>"52ea18324d61631e81010000"}}, "commit"=>"Create Service"}
MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} runtime: 0.6610ms
MOPED: 127.0.0.1:27017 UPDATE database=service_boot_camp_development collection=users selector={"band_id"=>BSON::ObjectId('52ea18834d61631e7e010000'), "_id"=>{"$nin"=>[]}} update={"$set"=>{"band_id"=>nil}} flags=[:multi]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 0.5800ms
MOPED: 127.0.0.1:27017 INSERT database=service_boot_camp_development collection=services documents=[{"_id"=>BSON::ObjectId('52ea18834d61631e7e020000'), "date"=>"2014-02-02", "time"=>"10:00", "place"=>"Where it's at", "name"=>"My great name", "theme"=>"The service's theme", "team"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e030000')}, "band"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e010000')}}] flags=[]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 2.7460ms
I guess I'm doing something wrong, but I have no clue if it is in the database model or in the form... or anything else...
You will not be able to do it this way. When you create an embedded document, its _id and all of its data are embedded directly within the parent document. This is in contrast to an association, where the document with the belongs_to gets a foreign key which points to its associated parent document. So here, your User documents each have a team_id and band_id, but when the database tries to get the documents, it can't find them, since you can't query directly for embedded documents; you need the parent document first. For more, see the Mongoid documentation.
Another potential issue is that you have multiple belongs_to definitions in the User models. This will also cause an issue, because for each one of those, Mongoid will attempt to create a team_id and band_id. You should name them separately and specify a class name; perhaps names like :presiding_team and :message_team, :lead_band and :guitar_band, etc. This answer should show you what that would look like.
I would recommend making the Team and Band separate referenced documents instead of embedded documents, since you won't be able to reference users effectively while they're embedded.
Hope this helps.

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