How do I get my rails app to use my postgresql db? - ruby-on-rails-4

I installed prostgres to use with my rails4 app, and I am able to connect to the database server and create databases. Then I made the necessary changes to my Gemfile and config/database.yml to use postgres. Then I created a new app, and in the app I created a User model:
$ rails generate model User name:string email:string
invoke active_record
create db/migrate/20130806145935_create_users.rb
create app/models/user.rb
invoke rspec
create spec/models/user_spec.rb
And then I did:
$ bundle exec rake db:migrate
== CreateUsers: migrating ====================================================
-- create_table(:users)
-> 0.1498s
== CreateUsers: migrated (0.1500s) ===========================================
But in the db directory, I see these files:
development.sqlite3
test.sqlite3
Furthermore, when I try to look at those files with the SQLite Database Browser, I get an error that says they are not sqlite 3 databases. In fact, they are empty:
~/rails_projects/sample_app4_0/db$ ls -al
total 40
drwxr-xr-x 8 7stud staff 272 Aug 6 22:50 .
drwxr-xr-x 24 7stud staff 816 Aug 6 22:23 ..
-rw-r--r-- 1 7stud staff 0 Jul 30 00:21 development.sqlite3
drwxr-xr-x 3 7stud staff 102 Aug 6 22:22 migrate
-rw-r--r-- 1 7stud staff 1063 Aug 6 09:06 schema.rb
-rw-r--r-- 1 7stud staff 343 Jul 29 20:01 seeds.rb
-rw-r--r-- 1 7stud staff 0 Jul 30 03:02 test.sqlite3
I read that you can create your rails app with a flag that tells it to use postgres:
rails new myapp --database postgresql
but I already created my app. Do I have to start over? I'm using git if that makes a difference.
My Gemfile:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
#Added for postgres:
gem 'pg', '0.15.1'
group :development, :test do
#gem 'sqlite3', '1.3.7'
gem 'rspec-rails', '2.13.1'
gem 'guard-rspec', '2.5.0'
gem 'spork-rails', github: 'sporkrb/spork-rails'
gem 'guard-spork', '1.5.0'
gem 'childprocess', '0.3.6'
end
group :test do
gem 'selenium-webdriver', '2.0.0'
gem 'capybara', '2.1.0'
gem 'growl', '1.0.3'
end
gem 'sass-rails', '4.0.0'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
#gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
config/database.yml:
development:
adapter: postgresql
encoding: utf8
database: sampleapp_dev #can be anything unique
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: postgresql
encoding: utf8
database: sampleapp_test #can be anything unique
pool: 5
timeout: 5000
production:
adapter: postgresql
database: sampleapp_prod
pool: 5
timeout: 5000

Okay, to figure out what's going on I created a new test app using the --database flag:
rails_projects$ rails new test_postgres --database postgresql
It turns out, all that does is set up your config/database.yml file like this:
development:
adapter: postgresql
encoding: unicode
database: test_postgres_development
pool: 5
username: test_postgres
password:
test:
adapter: postgresql
encoding: unicode
database: test_postgres_test
pool: 5
username: test_postgres
password:
production:
adapter: postgresql
encoding: unicode
database: test_postgres_production
pool: 5
username: test_postgres
password:
And the empty sqlite files:
development.sqlite3
test.sqlite3
were still present in the db directory.
Then I started up postgres, and I used pgAdmin3 to connect to the postgres database server. (If that is confusing, see: How do I start enterpiseDB PostgreSQL on Mac OSX 10.6.8?)
Then I created a model:
~/rails_projects$ cd test_postgres/
~/rails_projects/test_postgres$ rails g scaffold Post title:string author:string body:text
invoke active_record
create db/migrate/20130807061320_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
invoke resource_route
route resources :posts
invoke scaffold_controller
create app/controllers/posts_controller.rb
invoke erb
create app/views/posts
create app/views/posts/index.html.erb
create app/views/posts/edit.html.erb
create app/views/posts/show.html.erb
create app/views/posts/new.html.erb
create app/views/posts/_form.html.erb
invoke test_unit
create test/controllers/posts_controller_test.rb
invoke helper
create app/helpers/posts_helper.rb
invoke test_unit
create test/helpers/posts_helper_test.rb
invoke jbuilder
create app/views/posts/index.json.jbuilder
create app/views/posts/show.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/posts.js.coffee
invoke scss
create app/assets/stylesheets/posts.css.scss
invoke scss
create app/assets/stylesheets/scaffolds.css.scss
Then I tried to execute the migration:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
rake aborted!
FATAL: role "test_postgres" does not exist
...
...
That error occured because I don't have a database user(or role in postgres speak) named test_postgres--and it's likely no one else will either. When I set up postgres, I created the user 7stud, which is my Mac user name. To fix that rails error, I just changed the username to 7stud on the three lines in config/database.yml. Edit: in fact, I didn't even need to do that. Because I am the user 7stud on my Mac, that means I am executing my rails commands as 7stud, and coupled with the fact that my postgres db was setup with a user named 7stud, that allows me to completely eliminate the username line in config/database.yml:
development:
adapter: postgresql
encoding: unicode
database: test_postgres_development
pool: 5
test:
adapter: postgresql
encoding: unicode
database: test_postgres_test
pool: 5
production:
adapter: postgresql
encoding: unicode
database: test_postgres_production
pool: 5
Then I tried executing the migration again:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
rake aborted!
FATAL: database "test_postgres_development" does not exist
...
...
Notice that the database.yml file specifies three database names. So I created the development and test databases:
~$ cd /Library/PostgreSQL/9.2/
/Library/PostgreSQL/9.2$ sudo su postgres
Password: <normal sudo password>
bash-3.2$ createdb -O7stud -Eutf8 test_postgres_development
bash-3.2$ createdb -O7stud -Eutf8 test_postgres_test
-O owner
-E encoding
Then I tried executing the migration again:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
== CreatePosts: migrating ====================================================
-- create_table(:posts)
-> 0.0441s
== CreatePosts: migrated (0.0443s) ===========================================
Success (but elsewhere on the net examples show different output with 'Notice' lines).
Then I started a server:
~/rails_projects/test_postgres$ rails s
...and in my browser I entered the url:
http://localhost:3000/posts
...and I created a couple of Posts.
Then using pgAdmin3, I tried to find the posts in the test_postgres_development database. First, I refreshed the 'Databases(3)' line in pgAdmin3 by right clicking on the line and choosing 'Refresh'. Then I searched through the test_postgres_development directory for a long time, with no luck. Under Schemas, I could see a Tables directory that contained a posts directory, so the table got created, but I couldn't figure out how to see if there were any entries in the table. It turns out, you have to right click on the posts directory, then select 'View Data', and voila there were the posts I created.
Or you can view the entries using the command line:
~$ cd /Library/PostgreSQL/9.2/
/Library/PostgreSQL/9.2$ sudo su postgres
Password: <normal sudo password>
bash-3.2$ psql -U 7stud test_postgres_development
psql (9.2.4)
Type "help" for help.
test_postgres_development=> \dt
List of relations
Schema | Name | Type | Owner
--------+-------------------+-------+-------
public | posts | table | 7stud
public | schema_migrations | table | 7stud
(2 rows)
test_postgres_development=> \d posts
Table "public.posts"
Column | Type | Modifiers
------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(255) |
author | character varying(255) |
body | text |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
test_postgres_development=> select id, title, author, created_at from posts;
id | title | author | created_at
----+------------------------+--------------+----------------------------
1 | Hi there. | Tom | 2013-08-07 06:24:57.806237
2 | Ola! | Nancy | 2013-08-07 06:25:23.989643
(2 rows)
test_postgres_development=>

Related

Git Push to Rails Production Gives Response Your Ruby version is 1.9.3, but your Gemfile specified 2.2.2 When Ruby Version is 2.2.2

I have seen this error all over the place, but none of the solutions I have found have helped to fix the issue. I am developing a rails app locally on a Mac and have set up a droplet on DigitalOcean to push the app to. My droplet is running Ubuntu 14 and i am deploying using a Git post-receive hook. This is the hook:
#!/bin/bash
GIT_DIR=/home/xxx/yyy_production
WORK_TREE=/home/xxx/yyy
export XXX_DATABASE_USER='xxx'
export XXX_DATABASE_PASSWORD='12345'
export RAILS_ENV=production
. ~/.bashrc
while read oldrev newrev ref
do
if [[ $ref =~ .*/master$ ]];
then
echo "Master ref received. Deploying master branch to production..."
mkdir -p $WORK_TREE
git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f
mkdir -p $WORK_TREE/shared/pids $WORK_TREE/shared/sockets $WORK_TREE/shared/log
# start deploy tasks
cd $WORK_TREE
bundle install
rake db:create
rake db:migrate
rake assets:precompile
sudo restart puma-manager
sudo service nginx restart
# end deploy tasks
echo "Git hooks deploy complete"
else
echo "Ref $ref successfully received. Doing nothing: only the master branch may be deployed on this server."
fi
done
This is the output I get when I push:
Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 444 bytes | 0 bytes/s, done.
Total 5 (delta 4), reused 0 (delta 0)
remote: Master ref received. Deploying master branch to production...
remote: Your Ruby version is 1.9.3, but your Gemfile specified 2.2.2
remote: rake aborted!
remote: Bundler::RubyVersionMismatch: Your Ruby version is 1.9.3, but your Gemfile specified 2.2.2
I don't understand this at all, as I have installed ruby 2.2.2 and selected it using RVM. When I log on to the Ubuntu machine using ssh, I don't get any errors at all running bundler. Yet this is what it does when I run using my hook. I've been fighting with this for several days. Any help is greatly appreciated.
Just some additional info:
ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
rvm info
ruby-2.2.2:
system:
uname: "Linux mgots-app-01 3.13.0-68-generic #111-Ubuntu SMP Fri Nov 6 18:17:06 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux"
system: "ubuntu/14.04/x86_64"
bash: "/bin/bash => GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)"
zsh: " => not installed"
rvm:
version: "rvm 1.26.11 (master) by Wayne E. Seguin <wayneeseguin#gmail.com>, Michal Papis <mpapis#gmail.com> [https://rvm.io/]"
updated: "21 hours 6 minutes 30 seconds ago"
path: "/usr/share/rvm"
ruby:
interpreter: "ruby"
version: "2.2.2p95"
date: "2015-04-13"
platform: "x86_64-linux"
patchlevel: "2015-04-13 revision 50295"
full_version: "ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]"
homes:
gem: "/home/xxx/.rvm/gems/ruby-2.2.2"
ruby: "/usr/share/rvm/rubies/ruby-2.2.2"
binaries:
ruby: "/usr/share/rvm/rubies/ruby-2.2.2/bin/ruby"
irb: "/usr/share/rvm/rubies/ruby-2.2.2/bin/irb"
gem: "/usr/share/rvm/rubies/ruby-2.2.2/bin/gem"
rake: "/usr/share/rvm/rubies/ruby-2.2.2/bin/rake"
environment:
PATH: "/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/usr/share/rvm/rubies/ruby-2.2.2/bin:/usr/share/rvm/bin:/home/carl/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/home/xxx/.rbenv/plugins/ruby-build/bin:/home/xxx/.rbenv/shims:/home/xxx/.rbenv/bin:/home/xxx/.rvm/gems/ruby-2.2.2/bin:/home/xxx/.rvm/gems/ruby-2.2.2#global/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
GEM_HOME: "/home/xxx/.rvm/gems/ruby-2.2.2"
GEM_PATH: "/home/xxx/.rvm/gems/ruby-2.2.2:/home/xxx/.rvm/gems/ruby-2.2.2#global"
MY_RUBY_HOME: "/usr/share/rvm/rubies/ruby-2.2.2"
IRBRC: "/usr/share/rvm/rubies/ruby-2.2.2/.irbrc"
RUBYOPT: ""
gemset: ""
EDIT: posting further data per request
Gemfile
source 'https://rubygems.org'
ruby "2.2.2"
gem 'rails', '4.2.2'
gem 'pg'
gem 'bootstrap-sass', '3.3.5.1'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'font-awesome-rails'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'bcrypt', '~> 3.1.7'
gem 'geocoder', '1.2.12'
group :development, :test do
gem 'byebug'
gem 'web-console', '~> 2.0'
gem 'spring'
end
group :production do
gem 'puma'
gem 'therubyracer', platforms: :ruby
end
rvm list
rvm rubies
* ruby-2.2.1 [ x86_64 ]
=> ruby-2.2.2 [ x86_64 ]
# => - current
# =* - current && default
# * - default
~/.bashrc
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
if [[ -n "$PS1" ]]; then
# Some code here... e.g.
export HISTCONTROL=ignoreboth
fi
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session
On both your droplet and your mac, remove Gemfile.lock, make sure ruby -v responds with version 2.2, and do a bundle update.
These steps should reset everything. If they don't work, do a spring stop and reinstall bundler binstubs (if you use these tools).
Good luck!

Rails 4: How to add ENVIRONMENT VARIABLES on Ubuntu 14.04 using RVM?

Right now I'm trying to deploy my Ruby on Rails app to a Virtual Machine on Windows Azure running Ubuntu but I can fix de set environment variables error as below describe.
I have done added variables to my .bashrc and now in /etc/environment but the error is the same:
App 1227 stderr: [ 2015-10-06 04:10:57.3814 1352/0x9020d38(Worker 1) utils.rb:86 ]: *** Exception RuntimeError in Rack application object (Missing `secret_to$
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:534:in `validate_secret_$
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:246:in `env_config'
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/engine.rb:514:in `call'
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:165:in `call'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:94:in `process_request'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:151:in `accept_and_process_next_request'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:112:in `main_loop'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:112:in `block in create_thread_and_abort_on_exception'
[ 2015-10-06 04:10:57.3819 988/b5efeb40 age/Cor/Req/Utils.cpp:95 ]: [Client 1-1] Sending 502 response: application did not send a complete response
This is my sudo nano /etc/environment file:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
export SECRET_KEY_BASE=2da0d3f0bfd7b9b05110bfad512f42df2d2bb2ef715c4e831caba96a9c0b2141fbfa718dff2f5daf916cd70a70afd1f24df49884c561fbbaf364b36652b2c7d1
ruby -e 'p ENV["SECRET_KEY_BASE"]'
export MATCH_PEOPLE_DATABASE_PASSWORD=2015deployer
ruby -e 'p ENV["MATCH_PEOPLE_DATABASE_PASSWORD"]'
And when I run echo $SECRET_KEY_BASE or echo $MATCH_PEOPLE_DATABASE_PASSWORD I got the exact data.
deploy#vmw-ubuserver:~$ echo $SECRET_KEY_BASE
2da0d3f0bfd7b9b05110bfad512f42df2d2bb2ef715c4e831caba96a9c0b2141fbfa718dff2f5daf916cd70a70afd1f24df49884c561fbbaf364b36652b2c7d1
deploy#vmw-ubuserver:~$ echo $MATCH_PEOPLE_DATABASE_PASSWORD
2015deployer
But I still getting the same error in production, I'm using RVM, Capistrano, Passenger and NGINX on Ubuntu 14.04.
My database.yml :
production:
adapter: mysql2
encoding: utf8
pool: 5
host: localhost
database: matchpeople_production
username: deployer
password: <%= ENV['MATCH_PEOPLE_DATABASE_PASSWORD'] %>
My secrets.yml :
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
secret_token: <%= ENV["SECRET_KEY_BASE"] %>
Any kind of help?
Looking and looking for the correct answer I have been trying too many options but I didn't make it works fine.
So, suddenly I found I solution while I was testing some configurations found on google.
It is simple, just:
Add the next lines:
export SECRET_KEY_BASE=3aa7e349bh345h245hi23452345h234ih52i3u45h$
export MATCH_PEOPLE_DATABASE_PASSWORD=your_pass_here
# Uncomment these lines and restart the server to validate if the variables are read correctly
#ruby -e 'p ENV["SECRET_KEY_BASE"]'
#ruby -e 'p ENV["MATCH_PEOPLE_DATABASE_PASSWORD"]'
At the end of the files below:
sudo nano ~/.bash_profile
sudo nano /etc/environment
If you want you can uncomment the last two lines in ~/.bash_profile and restart your server and when you login to it again, you will see the value of the ENVIRONMENT VARIABLES before your promt as in the picture below.
I recommend you to keep those lines commented do it just for validate and then comment them again.
If you have any question, please leave a comment!
Hope it could be useful.
From my experience, there is no secret_token needed in secrets.yml for Ruby RVM.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
I think to solve the problem, remove the second line from your production: section
In case you need to add environment variables to RVM, edit
# /etc/profile.d/appspecific.sh
add something like
export GEM_PATH=/usr/local/rvm/gems/ruby-1.9.3-p551:/usr/local/rvm/gems/ruby-1.9.3-p551#global
export GEM_HOME=/usr/local/rvm/gems/ruby-1.9.3-p551
Good luck!

Ruby on Rails 4 Whenever cron job working but not sure about output

I am newbie on Ruby on rails.
I have to implement auto-generate mail functionality with cronjobs using whenever gem and I have followed this link http://www.sitepoint.com/schedule-cron-jobs-whenever-gem/
What I have done---
1. Added user_notifier.rb file and set all mail actions as
class UserNotifier < ActionMailer::Base
default from: "myusername#example.com"
def two_hour_reminder
mail( :to => 'username#example.com' ,:subject => 'Reminder')
end
def mail_notification
UserNotifier.two_hour_reminder.deliver
end
end
2. Added schedule.rb
every 3.minutes do
rake 'send_digest_email'
end
3. Added scheduler.rake
desc 'send digest email'
task send_digest_email: :environment do
UserNotifier.mail_notification.deliver!
end
4. Added deploy.rb
require 'whenever/capistrano'
set :whenever_environment, defer { stage }
set :whenever_command, 'bundle exec whenever'
After this I have executed command grep CRON /var/log/syslog where i got following log
CMD (/bin/bash -l -c 'cd /home/username/repository && RAILS_ENV=production
bundle exec rake send_digest_email --silent')
But still I'm not getting any mail in inbox.
What I´m missing?
In schedule.rb, replaced rake 'send_digest_email' with command 'cd /home/username/repository && RAILS_ENV=development
bundle exec rake send_digest_email --silent'
:)

With Rails 4 and selenium web driver, use Sauce Labs on Travis CI but not locally

I'm filling out specs for an open source Rails project and need to run the app in a browser for some of my feature specs. I'd like to use Sauce Labs on Travis CI, but without having to rewrite my specs to also use Sauce Labs locally, because:
I don't want to have to be connected to the Internet during development to run my specs.
Making the specs reliant on Sauce Labs would make it impossible for contributors to run the specs themselves without setting up their own Sauce Labs account and env vars.
I couldn't find documentation detailing this scenario. What's the best way of achieving this?
For those with similar needs, this is what I ended up doing:
.travis.yml:
env:
global:
- secure: "encrypted sauce username"
- secure: "encrypted sauce secret key"
addons:
sauce_connect: true
before_install:
# install the ed text editor which we use to append
# file contents to a specific line of another file
- sudo apt-get install -y ed
# appends contents of travis/Gemfile.travis to Gemfile
- cat travis/Gemfile.travis >> Gemfile
# adds contents of travis/rails_helper.rb.travis to line 12 of spec/rails_helper.rb
- ed -s spec/rails_helper.rb <<< '12r travis/rails_helper.rb.travis'$'\nw'
travis/Gemfile.travis:
group :test, :development do
gem 'sauce', '~> 3.1.1'
gem 'sauce-connect'
gem 'parallel_tests'
end
travis/rails_helper.rb.travis:
require 'sauce'
require 'sauce/capybara'
# change to "Capybara.default_driver = :sauce" to use sauce
# for ALL feature specs, not just ones marked with "js: true"
Capybara.javascript_driver = :sauce
Sauce.config do |config|
config[:browsers] = [
['Linux', 'Chrome', nil],
# and other OS/browser combos you want to support...
]
end
UPDATE (2014/11/25):
I ended up using a slightly different configuration in my final solution. I didn't like the brittleness of inserting at a line number. Instead of having special Sauce inclusions in separate files, I just nested special configuration in a conditional, depending on whether an environment variable SAUCY is set to true.
.travis.yml:
env:
global:
- secure: "encrypted sauce username"
- secure: "encrypted sauce secret key"
- SAUCY: true
addons:
sauce_connect: true
Gemfile:
group :development, :test do
# other gems...
if ENV['SAUCY']
# gems for sauce
gem 'sauce', '~> 3.1.1'
gem 'sauce-connect'
gem 'parallel_tests'
end
end
spec/rails_helper.rb:
# after other requires
if ENV['SAUCY']
require 'sauce'
require 'sauce/capybara'
# change to "Capybara.default_driver = :sauce" to use sauce
# for ALL feature specs, not just ones marked with "js: true"
Capybara.javascript_driver = :sauce
Sauce.config do |config|
config[:browsers] = [
['Linux', 'Chrome', nil],
# and other OS/browser combos you want to support...
]
end
end
This way, I can also easily use Sauce locally if I choose to with:
SAUCY=true bundle install
SAUCY=true SAUCE_USERNAME=username SAUCE_ACCESS_KEY=access_key bundle exec rspec

Splitting User and Profile issue

I'm probably missing something trivial...
I have a User model that 'has_one' UserProfile:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
has_many :user_roles, dependent: :destroy
has_many :roles, through: :user_roles
has_one :user_profile, dependent: :destroy
accepts_nested_attributes_for :user_roles, :user_profile, allow_destroy: true
validates :email, presence: true, format: {with: TextUtils::VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false}
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
def admin?
in_role?(Role::ADMINISTRATOR)
end
def in_role?(role)
!self.roles.find_by_name(role).nil?
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
and I have a UserProfile model that 'belongs_to' User:
class UserProfile < ActiveRecord::Base
belongs_to :user
has_one :address, dependent: :destroy
accepts_nested_attributes_for :address
validates :first, :last, :ssn, :title, :division, :phone_home, :phone_mobile, :phone_work, :phone_work_ext,
:emergency_phone, :emergency_name, :emergency_relation, presence: true
validates :personal_email, format: { with: TextUtils::VALID_EMAIL_REGEX }
end
When I try to seed the database as such (or any other way where profile is assigned to user):
# Admin
admin = User.create!(email: "admin#work.com", password: "secret", password_confirmation: "secret",
user_profile: UserProfile.new(
first: "Admin",
last: "User",
address_attributes: {line1: "123 Fake Street", line2: "Suite 1", city: "Some City", state: "FL", zip_code: "11111"},
ssn: "123-45-6789",
phone_work: "(111) 222-3333",
phone_work_ext: "110",
personal_email: "test#home.com")
)
I keep getting the following error:
rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute: user_profile_id
C:/work/Portal/db/seeds.rb:12:in `'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
I'm at a loss as to why this is happening. Any help will be appreciated! I am using Rails 4.1.4, if that matters.
Everything has to be passed as (nested) hash(es):
admin = User.create!({
email: "admin#work.com",
password: "secret",
password_confirmation: "secret",
user_profile_attributes: {
first: "Admin",
last: "User",
address_attributes: {
line1: "123 Fake Street",
line2: "Suite 1",
city: "Some City",
state: "FL",
zip_code: "11111"
},
ssn: "123-45-6789",
phone_work: "(111) 222-3333",
phone_work_ext: "110",
personal_email: "test#home.com"
}
})
Update
Working example:
$ rails new testapplication
create
create README.rdoc
create Rakefile
create config.ru
create .gitignore
create Gemfile
create app
create app/assets/javascripts/application.js
create app/assets/stylesheets/application.css
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create app/views/layouts/application.html.erb
create app/assets/images/.keep
create app/mailers/.keep
create app/models/.keep
create app/controllers/concerns/.keep
create app/models/concerns/.keep
create bin
create bin/bundle
create bin/rails
create bin/rake
create config
create config/routes.rb
create config/application.rb
create config/environment.rb
create config/secrets.yml
create config/environments
create config/environments/development.rb
create config/environments/production.rb
create config/environments/test.rb
create config/initializers
create config/initializers/backtrace_silencers.rb
create config/initializers/cookies_serializer.rb
create config/initializers/filter_parameter_logging.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/session_store.rb
create config/initializers/wrap_parameters.rb
create config/locales
create config/locales/en.yml
create config/boot.rb
create config/database.yml
create db
create db/seeds.rb
create lib
create lib/tasks
create lib/tasks/.keep
create lib/assets
create lib/assets/.keep
create log
create log/.keep
create public
create public/404.html
create public/422.html
create public/500.html
create public/favicon.ico
create public/robots.txt
create test/fixtures
create test/fixtures/.keep
create test/controllers
create test/controllers/.keep
create test/mailers
create test/mailers/.keep
create test/models
create test/models/.keep
create test/helpers
create test/helpers/.keep
create test/integration
create test/integration/.keep
create test/test_helper.rb
create tmp/cache
create tmp/cache/assets
create vendor/assets/javascripts
create vendor/assets/javascripts/.keep
create vendor/assets/stylesheets
create vendor/assets/stylesheets/.keep
run bundle install
Your user account isn't allowed to install to the system Rubygems.
You can cancel this installation and run:
bundle install --path vendor/bundle
to install the gems into ./vendor/bundle/, or you can enter your password
and install the bundled gems to Rubygems using sudo.
$ cd testapplication/
$ bundle install --path vendor/bundle
Fetching gem metadata from https://rubygems.org/..........
Resolving dependencies...
Installing rake 10.3.2
Installing i18n 0.6.11
Using json 1.8.1
Installing minitest 5.4.1
Installing thread_safe 0.3.4
Installing tzinfo 1.2.2
Installing activesupport 4.1.1
Installing builder 3.2.2
Installing erubis 2.7.0
Installing actionview 4.1.1
Installing rack 1.5.2
Installing rack-test 0.6.2
Installing actionpack 4.1.1
Installing mime-types 1.25.1
Installing polyglot 0.3.5
Installing treetop 1.4.15
Installing mail 2.5.4
Installing actionmailer 4.1.1
Installing activemodel 4.1.1
Installing arel 5.0.1.20140414130214
Installing activerecord 4.1.1
Using bundler 1.6.1
Installing coffee-script-source 1.8.0
Installing execjs 2.2.1
Installing coffee-script 2.3.0
Installing thor 0.19.1
Installing railties 4.1.1
Installing coffee-rails 4.0.1
Installing hike 1.2.3
Installing multi_json 1.10.1
Installing jbuilder 2.1.3
Installing jquery-rails 3.1.1
Installing tilt 1.4.1
Installing sprockets 2.11.0
Installing sprockets-rails 2.1.3
Installing rails 4.1.1
Installing rdoc 4.1.1
Installing sass 3.2.19
Installing sass-rails 4.0.3
Installing sdoc 0.4.1
Installing spring 1.1.3
Installing sqlite3 1.3.9
Installing turbolinks 2.3.0
Installing uglifier 2.5.3
Your bundle is complete!
It was installed into ./vendor/bundle
Post-install message from rdoc:
Depending on your version of ruby, you may need to install ruby rdoc/ri data:
<= 1.8.6 : unsupported
= 1.8.7 : gem install rdoc-data; rdoc-data --install
= 1.9.1 : gem install rdoc-data; rdoc-data --install
>= 1.9.2 : nothing to do! Yay!
$ ./bin/rails g model user
invoke active_record
create db/migrate/20140829201904_create_users.rb
create app/models/user.rb
invoke test_unit
create test/models/user_test.rb
create test/fixtures/users.yml
$ ./bin/rails g model user_profile user:references test:integer
invoke active_record
create db/migrate/20140829201916_create_user_profiles.rb
create app/models/user_profile.rb
invoke test_unit
create test/models/user_profile_test.rb
create test/fixtures/user_profiles.yml
$ ./bin/rake db:migrate
== 20140829201904 CreateUsers: migrating ======================================
-- create_table(:users)
-> 0.0012s
== 20140829201904 CreateUsers: migrated (0.0013s) =============================
== 20140829201916 CreateUserProfiles: migrating ===============================
-- create_table(:user_profiles)
-> 0.0010s
== 20140829201916 CreateUserProfiles: migrated (0.0010s) ======================
Then edited the user model:
class User < ActiveRecord::Base
has_one :user_profile
accepts_nested_attributes_for :user_profile
end
UserProfile is already correct:
class UserProfile < ActiveRecord::Base
belongs_to :user
end
and run the create statement:
$ ./bin/rails c
Loading development environment (Rails 4.1.1)
2.1.0 :001 > User.create({user_profile_attributes: {test: 5}})
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-08-29 20:21:41.860036"], ["updated_at", "2014-08-29 20:21:41.860036"]]
SQL (0.4ms) INSERT INTO "user_profiles" ("created_at", "test", "updated_at", "user_id") VALUES (?, ?, ?, ?) [["created_at", "2014-08-29 20:21:41.864624"], ["test", 5], ["updated_at", "2014-08-29 20:21:41.864624"], ["user_id", 1]]
(1.3ms) commit transaction
=> #<User id: 1, created_at: "2014-08-29 20:21:41", updated_at: "2014-08-29 20:21:41">
2.1.0 :002 > User.last.user_profile.inspect
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
UserProfile Load (0.3ms) SELECT "user_profiles".* FROM "user_profiles" WHERE "user_profiles"."user_id" = ? LIMIT 1 [["user_id", 1]]
=> "#<UserProfile id: 1, user_id: 1, test: 5, created_at: \"2014-08-29 20:21:41\", updated_at: \"2014-08-29 20:21:41\">"