Another Location.count" didn't change by 1 - ruby-on-rails
Location is basically an address with other information fields. This is my first app and I followed Hartl and others in building it, but ignored failing tests that I couldn't fix at the time. Now I'm trying to rectify that. I've looked at all the postings I found with this problem, but still can't figure it out (discussed at end). The app works, I can create new locations, so I think the error is with the test.
FAIL["test_should_create_location", LocationsControllerTest, 2017-02-28 12:02:08 -0800]
test_should_create_location#LocationsControllerTest (1488312128.31s)
"Location.count" didn't change by 1.
Expected: 4
Actual: 3
test/controllers/locations_controller_test.rb:21:in `block in <class:LocationsControllerTest>'
Edited location_controller_test.rb (The location controller test has 8 tests, this is the one that fails):
require 'test_helper'
class LocationsControllerTest < ActionController::TestCase
setup do
#location = locations(:one)
end
test "should create location" do
assert_difference('Location.count') do
post :create, location: { address: #location.address,
city: #location.city,
state: #location.state,
longitude: #location.longitude,
latitude: #location.latitude,
geom: #location.geom,
coords_not_locked: #location.coords_not_locked,
geocoded_with: #location.geocoded_with,
extant: #location.extant,
current_description: #location.current_description,
source: #location.source,
ref_link: #location.ref_link,
notes: #location.notes }
# debugger
end
assert_redirected_to location_path(assigns(:location))
end
locations_controller.rb:
class LocationsController < ApplicationController
helper_method :sort_column, :sort_direction
before_action :set_location, only: [:show, :edit, :update, :destroy]
def index
#locations = Location.all
# For sortable columns
#locations = Location.order(sort_column + " " + sort_direction)
end
def show
end
def new
#location= Location.new({:address=> "Use W E etc and St without PERIODS"})
repopulateResidResto()
end
def edit
end
def create
# Instantiate a new object using form parameters (notes here from Lynda>Skoglund)
#location = Location.new(location_params)
# Save the object
respond_to do |format|
if #location.save
# If save succeeds, redirect to the index action
format.html { redirect_to #location, notice: 'Address was successfully created.' }
format.json { render :show, status: :created, location: #location}
else
# If save fails, redisplay the form with information user filled in
format.html { render :new }
format.json { render json: #location.errors, status: :unprocessable_entity }
end
end
repopulateResidResto()
end # end create
def update
respond_to do |format|
if #location.update(location_params)
# If update succeeds, redirect to the show page
format.html { redirect_to #location, notice: 'Address was successfully updated.' }
format.json { render :show, status: :ok, location: #location }
else
# If update fails, redisplay the edit form for fixing
format.html { render :edit }
format.json { render json: #location.errors, status: :unprocessable_entity }
end
end
repopulateResidResto()
end # End update
def destroy
location = #location.destroy
respond_to do |format|
format.html { redirect_to locations_url, notice: "Location '#{location}' was successfully destroyed." }
format.json { head :no_content }
end
repopulateResidResto()
end
private
# Use callbacks to share common setup or constraints between actions.
def set_location
#location = Location.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def location_params
params.require(:location).permit(:address, :city, :state, :longitude, :latitude, :geom, :coords_not_locked, :geocoded_with, :extant, :current_description, :source, :ref_link, :notes)
end
def sort_column
Location.column_names.include?(params[:sort]) ? params[:sort] : "address"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
locations.yml:
one:
address: 1 Address1
city: Los Angeles
state: California
longitude: 99.99
latitude: 99.99
extant: false
current_description: MyString2
notes: Notes1
source: Source1
geocoded_with: geocoded_with_1
coords_not_locked: false
ref_link: ref_link_1
geom: 0101000020E61000008B187618938F5DC0C2189128B4064140
two:
address: 2 Address2
city: Los Angeles
state: California
longitude: 9.99
latitude: 9.99
extant: true
current_description: MyString
notes: MyString
source: MyString
geocoded_with: MyString
coords_not_locked: true
ref_link: MyString
geom: 0101000020E61000007B4963B48E8F5DC0467C2766BD064140
three:
address: 3 Address3
city: Los Angeles
state: California
longitude: 9.99
latitude: 9.99
extant: true
current_description: MyString
notes: MyString3
source: MyString3
geocoded_with: MyString3
coords_not_locked: true
ref_link: MyString3
geom: 0101000020E61000007B4963B48E8F5DC0467C2766BD064140
The model, location.rb:
class Location < ActiveRecord::Base
has_many :years, dependent: :destroy
has_many :people, through: :years
has_many :resto_resid_lines
def longlat
"#{longitude} #{latitude}"
end
def notes_plus_geocode
if notes == ""
"#{geocoded_with}"
else
"#{notes} #{geocoded_with}"
end
end
def full_address
full_address = "#{address}, #{city}, #{state}"
end
# For next and previous in show.
def next
Location.where(["id > ?", id]).first
end
def previous
Location.where(["id < ?", id]).last
end
geocoded_by :full_address
after_validation :geocode, :if => :coords_not_locked?
validates :address, length: { minimum: 5, maximum: 50 }, uniqueness: true
end
test_helper.rb
require 'simplecov'
SimpleCov.start
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
fixtures :all
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Logs in a test user.
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
post login_path, session: { email: user.email,
password: password,
remember_me: remember_me }
else
session[:user_id] = user.id
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_redirect)
end
end
If I turn the debugger on in the test, #location is
(byebug) pp #location
#<Location:0x007ff26ffa1ba8
id: 980190962,
address: "MyString21",
city: "MyString23",
state: "MyString25",
longitude: #<BigDecimal:7ff26ff96b40,'0.9999E2',18(27)>,
latitude: #<BigDecimal:7ff26ff96a50,'0.9999E2',18(27)>,
extant: false,
current_description: "MyString2",
notes: "MyString24",
created_at: Sun, 05 Mar 2017 18:46:12 UTC +00:00,
updated_at: Sun, 05 Mar 2017 18:46:12 UTC +00:00,
geom: "0101000020E61000008B187618938F5DC0C2189128B4064140",
source: "MyString",
geocoded_with: "MyString",
coords_not_locked: false,
ref_link: "MyString">
#<Location id: 980190962, address: "MyString21", city: "MyString23", state: "MyString25", longitude: #<BigDecimal:7ff26ff96b40,'0.9999E2',18(27)>, latitude: #<BigDecimal:7ff26ff96a50,'0.9999E2',18(27)>, extant: false, current_description: "MyString2", notes: "MyString24", created_at: "2017-03-05 18:46:12", updated_at: "2017-03-05 18:46:12", geom: "0101000020E61000008B187618938F5DC0C2189128B4064140", source: "MyString", geocoded_with: "MyString", coords_not_locked: false, ref_link: "MyString"
I'm not sure what to expect for this.
One posting that seemed relevant "User.count" didn't change by 1 - Rails had incomplete yml—I've triple checked mine, but maybe still missing something.
#ArtOfCode. Creating in console (I think this is what you're asking). And since id is nil and it doesn't appear in the database, you may be on the right track:
irb(main):004:0> location = Location.create( address: "1 Address1", city: "Los Angeles", state: "California", longitude: 99.99, latitude: 99.99, extant: false, current_description: "MyString2", notes: "MyString24", source: "MyString", geocoded_with: "MyString", coords_not_locked: false, ref_link: "MyString", geom: "0101000020E61000008B187618938F5DC0C2189128B4064140")
(0.2ms) BEGIN
Location Exists (0.4ms) SELECT 1 AS one FROM "locations" WHERE "locations"."address" = '1 Address1' LIMIT 1
SQL (2.5ms) INSERT INTO "locations" ("address", "state", "longitude", "latitude", "extant", "current_description", "notes", "source", "geocoded_with", "coords_not_locked", "ref_link", "geom", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING "id" [["address", "1 Address1"], ["state", "California"], ["longitude", "99.99"], ["latitude", "99.99"], ["extant", "f"], ["current_description", "MyString2"], ["notes", "MyString24"], ["source", "MyString"], ["geocoded_with", "MyString"], ["coords_not_locked", "f"], ["ref_link", "MyString"], ["geom", "0101000020E61000008B187618938F5DC0C2189128B4064140"], ["created_at", "2017-03-05 20:00:28.246188"], ["updated_at", "2017-03-05 20:00:28.246188"]]
(2.1ms) COMMIT
#<Location:0x007fe851a9bac8> {
:id => 177,
:address => "1 Address1",
:city => "Los Angeles",
:state => "California",
:longitude => 99.99,
:latitude => 99.99,
:extant => false,
:current_description => "MyString2",
:notes => "MyString24",
:created_at => Sun, 05 Mar 2017 20:00:28 UTC +00:00,
:updated_at => Sun, 05 Mar 2017 20:00:28 UTC +00:00,
:geom => "0101000020E61000008B187618938F5DC0C2189128B4064140",
:source => "MyString",
:geocoded_with => "MyString",
:coords_not_locked => false,
:ref_link => "MyString"
}
The application is incomplete, but you can see a location here. Not currently allowing sign-ups, so obviously create can't be used. The addresses are more than 100 years old and the geo coordinates may not be generated. geom is created later in PostGIS.
I imagine there is a simple solution, but it alludes me. gem 'rails' , '4.2.7' and ruby '2.3.1'
Fixtures create database entries automatically. Your location fixture one exists in the database.
So when you try a post to create a new location and you specify...
post :create, location: { address: #location.address,
You are trying to create a location with an address that already exists, but
validates :address, length: { minimum: 5, maximum: 50 }, uniqueness: true
...specifies that the address must be unique, so the record you're attempting to post is not valid because it has the same address as an existing record.
Simply change the address in your post :create call
post :create, location: { address: "1 A New Address",
Related
How to write optimistic locking test cases in Rails
I need to test if my implementation of optimistic locking is correct or not. But I don't know how to test my functionalities. Here is the update action I wrote: def update begin #update_operator = Operator.find(params[:id]) authorize! :update, #update_operator if #update_operator.update_attributes(operator_params) render json: #update_operator, except: :badge else render json: #update_operator.errors, status: :unprocessable_entity end rescue ActiveRecord::StaleObjectError #update_operator.reload retry end end And here is the migration I added class AddLockingColumnsToOperators < ActiveRecord::Migration[5.1] def up add_column :operators, :lock_version, :integer, :default => 0, :null => false end def down remove_column :operators, :lock_version end end Can anyone tell me how to test the update action above with rspec? Update: Here is the attempt I tried, but it didn't work let!(:operator1) { FactoryBot.create(:operator, :site => site) } let!(:attributes) { { id: operator1.id, first_name: "test1", last_name: "test2", employee_number: "tesnt12345", badge: "test215235", suspended: true, site_id: site.id } } let!(:stale_attributes) { { id: operator1.id, first_name: "test_fake", last_name: "test_fake", employee_number: "tesnt12345", badge: "test215235", suspended: true, site_id: site.id } } it("cause StaleObjectError when updating same operator at the same time") do patch :update, params: { :id => operator1.id, :operator => attributes } patch :update, params: { :id => operator1.id, :operator => stale_attributes } expect(response).to raise_error(ActiveRecord::StaleObjectError) end
You want a test case where optimistic locking fails. First get your edit form. Then update the record from an independent update. Then submit the edit form. In a functional test it might look like this: visit "/operators/#{operator.id}/edit" indep_operator = Operator.find(operator.id) indep_operator.update!( ... some attributes ...) fill_in "Name", :with => "New Value" click_button "Update Operator"
ActiveRecord not updating dirty attribute on save / update. Create OK. Possible Inheritance issue
I have a class structure using single table inheritance as follows: CashAccount > AssetAccount > FinancialAccount Relavent Controller Code: def create #financial_account = FinancialAccount.new(financial_account_params) respond_to do |format| if #financial_account.save format.html { redirect_to #financial_account, notice: 'Account was successfully created.' } else format.html { render :new } end end end def update respond_to do |format| if #financial_account.update(financial_account_params) format.html { redirect_to #financial_account, notice: 'Account was successfully updated.' } else format.html { render :edit } end end end def set_financial_account #financial_account = FinancialAccount.find_by_id(params[:id]) unless #financial_account redirect_to root_path, :flash => { :alert => "That Account does not exist." } return end end def update_params params.require(#financial_account.model_name.param_key) .permit(:name, :type, :description) end def create_params params.require(:financial_account) .permit(:name, :type, :description) end Create works. Update does not. There are no errors. The saves return true but the value is never changed. Here are some puts to debug the state as the object is updated: puts #financial_account.changed? //false #financial_account.assign_attributes(financial_account_params) puts #financial_account.changed? //true #financial_account.description_will_change! puts #financial_account.changed? //true puts #financial_account.description //New Value 1 puts #financial_account.save //true puts #financial_account.description //Old Value puts #financial_account.update(:description => "New Value 2") //true puts #financial_account.description //Old Value #financial_account.description = "New Value 3" puts #financial_account.description //New Value 3 puts #financial_account.save //true puts #financial_account.description //Old Value Description is a simple text attribute of the FinancialAccount Class: create_table "financial_accounts", id: :uuid, default: "uuid_generate_v4()", force: :cascade do |t| ... t.text "description" ... end partial to_yaml print out of #financial_account to view stored value form user: delegate_hash: name: !ruby/object:ActiveRecord::Attribute::FromUser name: name value_before_type_cast: Test Account type: *1 value: Test Account description: !ruby/object:ActiveRecord::Attribute::FromUser name: description value_before_type_cast: New Value 1 type: *1 value: New Value 1 The database is PostgreSQL UPDATE - Output requested by DjezzzL Note: This is a multi-tenant app so i need to set business id 2.2.4 :001 > Business.current_id = 1 => 1 2.2.4 :002 > tmp = FinancialAccount.first FinancialAccount Load (0.6ms) SELECT "financial_accounts".* FROM "financial_accounts" WHERE "financial_accounts"."business_id" = $1 ORDER BY "financial_accounts"."id" ASC LIMIT 1 [["business_id", 1]] => #<RetainedEarningsAccount id: "0a282a84-2561-4820-8f21-b8063c1c2604", type: "RetainedEarningsAccount", name: "Owner's Retained Earnings", created_at: "2017-05-02 05:20:22", updated_at: "2017-05-02 05:20:22", description: "Old Value", business_id: 1, update_balance_flag: false, reference_number: "11", balance_cents: 0> 2.2.4 :003 > tmp.description = 'new value' => "new value" 2.2.4 :004 > p tmp.save (0.2ms) BEGIN FinancialAccount Exists (1.0ms) SELECT 1 AS one FROM "financial_accounts" WHERE ("financial_accounts"."reference_number" = '11' AND "financial_accounts"."id" != '0a282a84-2561-4820-8f21-b8063c1c2604' AND "financial_accounts"."business_id" = 1) LIMIT 1 RetainedEarningsAccount Load (0.3ms) SELECT "financial_accounts".* FROM "financial_accounts" WHERE "financial_accounts"."type" IN ('RetainedEarningsAccount') AND "financial_accounts"."id" = $1 LIMIT 1 [["id", "0a282a84-2561-4820-8f21-b8063c1c2604"]] (0.2ms) COMMIT true => true 2.2.4 :005 > p tmp.description "Old Value" => "Old Value" 2.2.4 :006 > p tmp.reload.description RetainedEarningsAccount Load (2.1ms) SELECT "financial_accounts".* FROM "financial_accounts" WHERE "financial_accounts"."type" IN ('RetainedEarningsAccount') AND "financial_accounts"."id" = $1 LIMIT 1 [["id", "0a282a84-2561-4820-8f21-b8063c1c2604"]] "Old Value" => "Old Value" Note: my attributes are being marked as dirty so not a duplicate of ActiveRecord not saving after updating attribute
def create #financial_account = FinancialAccount.new(create_params) respond_to do |format| if #financial_account.save format.html { redirect_to #financial_account, notice: 'Account was successfully created.' } else format.html { render :new } end end end def update respond_to do |format| if #financial_account.update(update_params) format.html { redirect_to #financial_account, notice: 'Account was successfully updated.' } else format.html { render :edit } end end end private def create_params params.require(#financial_account.model_name.param_key) .permit(:name, :type, :description) end def update_params params.require(:financial_account) .permit(:name, :type, :description) end Use ActiveModel::Naming#param_key to get the param key for a polymorphic model. Also in this case its better to use two separate methods for whitelisting as it reduces the amount of code paths.
Field with type data Array always return nil on conditional validation
I have model Campaign with fields : class Campaign field :title, type: String field :start_date, type: Date field :end_date, type: Date field :locations, type: Array, default: [] field :is_deleted, type: Boolean, default: false field :disabled, type: Boolean, default: false validate: :conflict_date, if: :check_location belongs_to :native_ad private def check_location locations.include?('Location 1') || locations.include?('Location 2') end def conflict_date ## another condition end end In create & update record action is working and value of locations is exists on check_location method but, when updating single attribute like : def destroy #campaign = Campaign.find(params[:id]) #campaign.update_attributes(is_deleted: true) ## other stuff end locations always return nil debugger on check_location method : [1] pry(#<Campaign>)> locations => nil [2] pry(#<Campaign>)> self => #<Campaign _id: 58ca3fa7fe37a86982000000, created_at: 2017-03-16 07:32:59 UTC, updated_at: 2017-03-16 07:32:59 UTC, start_date: 2017-03-16 00:00:00 UTC, end_date: 2018-03-16 00:00:00 UTC, locations: nil, disabled: false, is_deleted: true, native_ad_id: BSON::ObjectId('58ca3b52fe37a86590000000')> [3] pry(#<Campaign>)> end_date => Fri, 16 Mar 2018 [4] pry(#<Campaign>)> start_date => Thu, 16 Mar 2017 note : value of locations is exist in database create action def create #campaign = Campaign.new(campaign_params) if #campaign.save redirect_to campaigns_path else render :new end end private def campaign_params params.require(:campaign).permit(:start_date, :end_date, :native_ad, locations: []) end I'm use : Rails. 4.2.4 Mongoid 5.0.0
Why is this reject_if in my model not rejecting blank records?
In the following class... class Parent < ActiveRecord::Base has_many :relatives has_many :kids, through: :relatives accepts_nested_attributes_for :relatives, :reject_if => lambda { |a| a['kid_id'].blank? }, :allow_destroy => true end ...I've added some code which I expected to prevent 'relatives' from saving on the parent model if their fields were blank. It doesn't seem to work. It saved both blank and non-blank fields. I.e. when I go into the console and query the database, I can pull out the parent record and run queries like so: 2.2.2 :004 > p.relatives.find(17) Relative Load (5.4ms) SELECT "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1 [["parent_id", 24], ["id", 17]] => #<Relative id: 17, relationship: "yes", parent_id: 24, kid_id: 1, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07"> That's what I expected - I entered data for that 'kid'. 2.2.2 :005 > r = p.relatives.find(18) Relative Load (3.4ms) SELECT "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1 [["parent_id", 24], ["id", 18]] => #<Relative id: 18, relationship: "", parent_id: 24, kid_id: nil, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07"> This record should never have saved because it violates the lambda above, i.e. ... 2.2.2 :006 > r.relationship.blank? => true 2.2.2 :007 > r.kid.blank? => true ...the fields are blank! Here's the controller in question (extract): class ParentsController < ApplicationController before_action :set_parent, only: [:show, :edit, :update, :destroy] before_action :lookup_kids, only: [:new, :edit] # GET /parents/new def new #parent = Parent.new 4.times { #parent.relatives.build } end # POST /parents # POST /parents.json def create logger.debug(" SANITY CHECK ") logger.debug(parent_params) #parent = Parent.new(parent_params) parent_params[:relatives_attributes].each do |k,r| #parent.relatives.build(r.except(:_destroy)) end respond_to do |format| if #parent.save format.html { redirect_to #parent, notice: 'Parent was successfully created.' } format.json { render :show, status: :created, location: #parent } else format.html { render :new } format.json { render json: #parent.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_parent #parent = Parent.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def parent_params params.require(:parent).permit(:name, relatives_attributes: [:parent_id, :kid_id, :relationship, :_destroy]) end def lookup_kids #kids = Kid.all end end
I think this might help https://fabianosoriani.wordpress.com/2011/06/07/accepts_nested_attributes_for-3-0-5-reject_if-still-have-gotchas/ There are some gotchas behind accepts_nested_attributes_for with validations.
Based on my understanding since model kid is associated by Relative, you should do like this. Try this in your Parent Model accepts_nested_attributes_for :relatives, :allow_destroy => true Then in Your Relative Model, accepts_nested_attributes_for :kids, :reject_if => lambda { |a| a['kid_id'].blank? }, :allow_destroy => true
Thanks to #user5554692, discovered the only way to do this is as follows: Adding this to the parent controller: parent_params[:relatives_attributes].delete_if { |k,v| v['kid_id'].blank?} Removed all blank records, then... #parent = Parent.new(parent_params) Creates the parent object as usual. Apparently, reject_if just doesn't work in this particular scenario, for some reason.
rails db column remember_token is not saved and always nil? [duplicate]
This question already has answers here: ".save" only inserts null values in database (3 answers) Closed 8 years ago. Why am i unable to update a db column in rails? Database has a column - 'remember_token' but update is not working on it ? Result of DB migration .... .... .... == 20140830041234 AddRememberTokenToUsers: migrating ========================== -- add_column(:users, :remember_token, :string) -> 0.0010s -- add_index(:users, :remember_token) -> 0.0000s == 20140830041234 AddRememberTokenToUsers: migrated (0.0030s) ================= rails console - output ! remember_token is nil after a direct assignment irb(main):063:0* user => #<User id: 1, name: "Test", email: "hb#c.co", created_at: "2014-09-01 22:52:02", updated_at: "2014-09-01 22:52:02", p assword_digest: "$2a$10$/66wO2dBte/xCXqxk.UAo.v.7.XZjsBFA3AerAWkHp16...", remember_token: nil> irb(main):064:0> User.digest('asdasd') => "85136c79cbf9fe36bb9d05d0639c70c265c18d37" irb(main):065:0> user.remember_token = User.digest('asdasd') => "85136c79cbf9fe36bb9d05d0639c70c265c18d37" irb(main):066:0> irb(main):067:0* user => #<User id: 1, name: "Test", email: "hb#c.co", created_at: "2014-09-01 22:52:02", updated_at: "2014-09-01 22:52:02", p assword_digest: "$2a$10$/66wO2dBte/xCXqxk.UAo.v.7.XZjsBFA3AerAWkHp16...", remember_token: nil> irb(main):068:0> remember_token is nil after update_attributes irb(main):071:0> user.update_attributes(name: "Yahoo", remember_token: "will this get saved") ←[1m←[36m (0.0ms)←[0m ←[1mbegin transaction←[0m ←[1m←[35mUser Exists (1.0ms)←[0m SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('hb#c.co') AND "u sers"."id" != 1) LIMIT 1 ←[1m←[36mSQL (7.0ms)←[0m ←[1mUPDATE "users" SET "name" = ?, "updated_at" = ? WHERE "users"."id" = 1←[0m [["name", "Y ahoo"], ["updated_at", Mon, 01 Sep 2014 23:12:59 UTC +00:00]] ←[1m←[35m (8.0ms)←[0m commit transaction => true irb(main):072:0> irb(main):073:0* user => #<User id: 1, name: "Yahoo", email: "hb#c.co", created_at: "2014-09-01 22:52:02", updated_at: "2014-09-01 23:12:59", password_digest: "$2a$10$/66wO2dBte/xCXqxk.UAo.v.7.XZjsBFA3AerAWkHp16...", remember_token: nil> Below is the model class User < ActiveRecord::Base attr_accessor :remember_token before_save { self.email = email.downcase } before_create :create_remember_token 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 And just in case -- here is the controller class UsersController < ApplicationController def new #user = User.new end def show #user = User.find(params[:id]) end def create ##user = User.new(params.require(:user).permit(:name, :email, :password, :password_confirmation) #user = User.new(user_params) if #user.save # Handle a successful save. flash[:success] = "Welcome #{#user.name} to the Sample App!" redirect_to #user else render 'new' end end private def user_params params.require(:user).permit(:name, :email, :password,:password_confirmation, :remember_token) end end
You have to add :remember_token to attr_accessible in your User model. attr_accessible :remember_token
it seems that the :remember_token attribute has not been picked up by rails. Try to restart the console and it might work.