I'm doing the Hartl tutorial and my rails app works fine in development, but crashes in heroku with this error code:
application_controller.rb:5:in `<class:ApplicationController>': uninitialized constant ApplicationController::SessionsHelper (NameError)
This happened after I added a remember_digest to the schema. Not sure if it's migrations or an issue between SessionsHelper and ApplicationController
ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
sessions_helper.rb located in app/helpers
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Logs out the current user.
def log_out
forget(current_user)
session.delete(:user_id)
#current_user = nil
end
end
I tried deleting my old heroku app and starting a new one to reset the migrations (worked to "troubleshoot" in the past) but it didnt work this time. All of the migrations are showing up when I ran heroku rake db:migrate except the remember digest one. I ran db:migrate again but can't get it to migrate. Here are migrations:
Migrate.db
20150204074511_create_users.rb 20150204093042_add_phone_number_to_users.rb
20150204081616_add_index_to_users_email.rb 20150204094519_add_index_to_users_phone_number.rb
20150204081750_add_password_digest_to_users.rb 20150207093225_add_remember_digest_to_users.rb
Migrate logs
ajhausdorf#rails-tutorial:~/workspace/AccessOBD (master) $ heroku run rake db:migrate
Running `rake db:migrate` attached to terminal... up, run.4474
(18.0ms) CREATE TABLE "schema_migrations" ("version" character varying NOT NULL)
(8.6ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
ActiveRecord::SchemaMigration Load (1.5ms) SELECT "schema_migrations".* FROM "schema_migrations"
Migrating to CreateUsers (20150204074511)
(0.9ms) BEGIN
== 20150204074511 CreateUsers: migrating ======================================
-- create_table(:users)
(15.1ms) CREATE TABLE "users" ("id" serial primary key, "name" character varying, "email" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
-> 0.0162s
== 20150204074511 CreateUsers: migrated (0.0164s) =============================
SQL (1.2ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204074511"]]
(4.0ms) COMMIT
Migrating to AddIndexToUsersEmail (20150204081616)
(0.8ms) BEGIN
== 20150204081616 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true})
(4.6ms) CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")
-> 0.0081s
== 20150204081616 AddIndexToUsersEmail: migrated (0.0082s) ====================
SQL (0.9ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204081616"]]
(5.5ms) COMMIT
Migrating to AddPasswordDigestToUsers (20150204081750)
(0.7ms) BEGIN
== 20150204081750 AddPasswordDigestToUsers: migrating =========================
-- add_column(:users, :password_digest, :string)
(1.3ms) ALTER TABLE "users" ADD "password_digest" character varying
-> 0.0022s
== 20150204081750 AddPasswordDigestToUsers: migrated (0.0023s) ================
SQL (0.8ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204081750"]]
(1.7ms) COMMIT
Migrating to AddPhoneNumberToUsers (20150204093042)
(0.7ms) BEGIN
== 20150204093042 AddPhoneNumberToUsers: migrating ============================
-- add_column(:users, :phone, :string)
(1.4ms) ALTER TABLE "users" ADD "phone" character varying
-> 0.0023s
== 20150204093042 AddPhoneNumberToUsers: migrated (0.0024s) ===================
SQL (0.9ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204093042"]]
(2.8ms) COMMIT
Migrating to AddIndexToUsersPhoneNumber (20150204094519)
(4.4ms) BEGIN
== 20150204094519 AddIndexToUsersPhoneNumber: migrating =======================
-- add_index(:users, :phone, {:unique=>true})
(7.5ms) CREATE UNIQUE INDEX "index_users_on_phone" ON "users" ("phone")
-> 0.0110s
== 20150204094519 AddIndexToUsersPhoneNumber: migrated (0.0111s) ==============
SQL (0.8ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204094519"]]
(4.7ms) COMMIT
Is there a reason that this migration may not be going through? Running db:migrate again doesn't give any results. Any information on where you think the problem may be located even would be helpful, I cannot find any info on what's causing this.
My problem was that git wasn't tracking any of the sessions files I had added, so they were on my local computer but not on github->heroku. I found this out by making a change only on sessions_helper, then committing to git only to get a message that there were no changes to any files but several (all of the sessions files) were untracked.
Happened because I used git -am "commit message" rather than git add -A first bc I thought the -a flag added everything. Should've checked git to make sure sessions_helper.rb was there, all the answers told me to check this but I was only checking on my local machine.
Related
I have a simple migration which fails: The database is not affected, it still contains the old column name after migrating.
class RenameTypeToLicenseTypeInLicenses < ActiveRecord::Migration[5.1]
def change
rename_column :licenses, :type, :license_type
end
end
Renaming type to license_type is necessary because of this error:
The single-table inheritance mechanism failed to locate the subclass: 'creative commons'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite License.inheritance_column to use another column for that information.
This is the output of rails db:migrate
igrating to RenameTypeToLicenseTypeInLicenses (20210422110849)
(0.2ms) BEGIN
== 20210422110849 RenameTypeToLicenseTypeInLicenses: migrating ================
== 20210422110849 RenameTypeToLicenseTypeInLicenses: migrated (0.0000s) =======
SQL (0.9ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version" [["version", "20210422110849"]]
(1.4ms) COMMIT
ActiveRecord::InternalMetadata Load (0.5ms) SELECT "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2 [["key", "environment"], ["LIMIT", 1]]
(0.3ms) BEGIN
(0.3ms) COMMIT
(0.4ms) SELECT pg_advisory_unlock(2195010657070977375)
(0.6ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
How can I rename the type column?
edit:
As there's only little data in the table, I tried another approach:
remove_column :licenses, :type, :string
add_column :licenses, :license_type, :string
It doesn't work either. Output is
[NAME COLLISION] `type` is a reserved key in LicenseResource.
(0.7ms) SELECT pg_try_advisory_lock(2195010657070977375);
(1.3ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Migrating to ChangeTypeToLicenseTypeFromLicenses (20210422122638)
(0.5ms) BEGIN
== 20210422122638 ChangeTypeToLicenseTypeFromLicenses: migrating ==============
== 20210422122638 ChangeTypeToLicenseTypeFromLicenses: migrated (0.0000s) =====
SQL (1.0ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version" [["version", "20210422122638"]]
(4.6ms) COMMIT
ActiveRecord::InternalMetadata Load (0.4ms) SELECT "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2 [["key", "environment"], ["LIMIT", 1]]
(0.4ms) BEGIN
(0.4ms) COMMIT
(0.6ms) SELECT pg_advisory_unlock(2195010657070977375)
(0.9ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Yeah, I wonder if ActiveRecord's migration code might be trying its best to keep type intact, on the assumption that it's currently being used for single table inheritance; it's oblivious to the fact you want to change it because it currently isn't 😊
There may be an idiomatic Rails way of telling the migration that what you're doing is fine, but to be honest I'd be tempted to drop down to the SQL level, thus bypassing Rails' erroneous protection:
class RenameTypeToLicenseTypeInLicenses < ActiveRecord::Migration[5.1]
def up
execute <<~SQL
ALTER TABLE licenses RENAME COLUMN type TO license_type;
SQL
end
def down
execute <<~SQL
ALTER TABLE licenses RENAME COLUMN license_type TO type;
SQL
end
end
As you're not using migration commands, you have to provide separate up/down code for both directions of the migration.
I believe this answer should help you: issue with column name 'type' in rails 3
type is one of those reserved words we shouldn't use. Check other reserved words here: https://riptutorial.com/ruby-on-rails/example/32446/reserved-word-list
I've Ctrl+C my Rails server and rebooted the machine, but Puma keeps running an old version of the code.
Redirected to http://printrdwn.com:3000/
(0.3ms) BEGIN
↳ app/controllers/users/registrations_controller.rb:17
Role Load (1.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/users/registrations_controller.rb:17
(0.3ms) ROLLBACK
↳ app/controllers/users/registrations_controller.rb:17
(0.2ms) BEGIN
On Line 17 Puma queries the Role Model. There is no reference to the Role Model in my code. Here is the users/registrations_controller.rb, which inherits devise:
class Users::RegistrationsController < Devise::RegistrationsController
def create
super
#team = Team.new(name: "Personal")
TeamMember.create(user_id: current_user, team_id: #team.id, role_id: 1)
#team.save
end
end
In a past version of the user/registrations_controller I did reference Role in order to select the Administrator role, but that was unecessary. I've been trying to get the users/registrations_controller to create a Team and the current_user as a TeamMember, but then I realized my code didn't ever change with my corrections.
You want to pass a block to super so that the team is only created if the user is actually persisted:
class Users::RegistrationsController < Devise::RegistrationsController
def create
super do |user|
#team = Team.new(name: "Personal")
#team.members.new(user: user, role_id: 1)
#team.save
end
end
end
And building the record off the association will make sure that Rails actually saves both records in the same transaction. Passing ids explicitly is a code smell and in this case actually a bug as #team.id is nil as the record was not saved.
I am trying to migrate my app to heroku and this error came up, causing a rollback of my migration. Can anyone tell me why is there an error with date_time?
remembrance:~/rails_project/alpha-blog (master) $ heroku run rake db:migrate
Running rake db:migrate on ⬢ alpha-blog-javier... up, run.4829
ActiveRecord::SchemaMigration Load (1.9ms) SELECT "schema_migrations".* FROM "schema_migrations"
Migrating to AddDescriptionToArticles (20160816052220)
(1.7ms) BEGIN
== 20160816052220 AddDescriptionToArticles: migrating =========================
-- add_column(:articles, :description, :text)
(2.1ms) ALTER TABLE "articles" ADD "description" text
-> 0.0024s
-- add_column(:articles, :created_at, :date_time)
(4.1ms) ALTER TABLE "articles" ADD "created_at" date_time
(1.7ms) ROLLBACK
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedObject: ERROR: type "date_time" does not exist
LINE 1: ALTER TABLE "articles" ADD "created_at" date_time
It should be datetime not date_time. Read the documentation.
Change this line
add_column(:articles, :created_at, :date_time)
in your migration to
add_column(:articles, :created_at, :datetime)
I'm doing the Hartl tutorial and my rails app works fine in development, but crashes in heroku with this error code:
application_controller.rb:5:in `<class:ApplicationController>': uninitialized constant ApplicationController::SessionsHelper (NameError)
This happened after I added a remember_digest to the schema. Not sure if it's migrations or an issue between SessionHelper and ApplicationController
ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
Sessions_Helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Logs out the current user.
def log_out
forget(current_user)
session.delete(:user_id)
#current_user = nil
end
end
I tried deleting my old heroku app and starting a new one to reset the migrations (worked to "troubleshoot" in the past) but it didnt work this time. All of the migrations are showing up when I ran heroku rake db:migrate except the remember digest one. I ran db:migrate again but can't get it to migrate. Here are migrations:
Migrate.db
20150204074511_create_users.rb 20150204093042_add_phone_number_to_users.rb
20150204081616_add_index_to_users_email.rb 20150204094519_add_index_to_users_phone_number.rb
20150204081750_add_password_digest_to_users.rb 20150207093225_add_remember_digest_to_users.rb
Migrate logs
ajhausdorf#rails-tutorial:~/workspace/AccessOBD (master) $ heroku run rake db:migrate
Running `rake db:migrate` attached to terminal... up, run.4474
(18.0ms) CREATE TABLE "schema_migrations" ("version" character varying NOT NULL)
(8.6ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
ActiveRecord::SchemaMigration Load (1.5ms) SELECT "schema_migrations".* FROM "schema_migrations"
Migrating to CreateUsers (20150204074511)
(0.9ms) BEGIN
== 20150204074511 CreateUsers: migrating ======================================
-- create_table(:users)
(15.1ms) CREATE TABLE "users" ("id" serial primary key, "name" character varying, "email" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
-> 0.0162s
== 20150204074511 CreateUsers: migrated (0.0164s) =============================
SQL (1.2ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204074511"]]
(4.0ms) COMMIT
Migrating to AddIndexToUsersEmail (20150204081616)
(0.8ms) BEGIN
== 20150204081616 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true})
(4.6ms) CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")
-> 0.0081s
== 20150204081616 AddIndexToUsersEmail: migrated (0.0082s) ====================
SQL (0.9ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204081616"]]
(5.5ms) COMMIT
Migrating to AddPasswordDigestToUsers (20150204081750)
(0.7ms) BEGIN
== 20150204081750 AddPasswordDigestToUsers: migrating =========================
-- add_column(:users, :password_digest, :string)
(1.3ms) ALTER TABLE "users" ADD "password_digest" character varying
-> 0.0022s
== 20150204081750 AddPasswordDigestToUsers: migrated (0.0023s) ================
SQL (0.8ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204081750"]]
(1.7ms) COMMIT
Migrating to AddPhoneNumberToUsers (20150204093042)
(0.7ms) BEGIN
== 20150204093042 AddPhoneNumberToUsers: migrating ============================
-- add_column(:users, :phone, :string)
(1.4ms) ALTER TABLE "users" ADD "phone" character varying
-> 0.0023s
== 20150204093042 AddPhoneNumberToUsers: migrated (0.0024s) ===================
SQL (0.9ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204093042"]]
(2.8ms) COMMIT
Migrating to AddIndexToUsersPhoneNumber (20150204094519)
(4.4ms) BEGIN
== 20150204094519 AddIndexToUsersPhoneNumber: migrating =======================
-- add_index(:users, :phone, {:unique=>true})
(7.5ms) CREATE UNIQUE INDEX "index_users_on_phone" ON "users" ("phone")
-> 0.0110s
== 20150204094519 AddIndexToUsersPhoneNumber: migrated (0.0111s) ==============
SQL (0.8ms) INSERT INTO "schema_migrations" ("version") VALUES ($1) [["version", "20150204094519"]]
(4.7ms) COMMIT
How can I get this last migration to work?
My problem was that git wasn't tracking any of the sessions files I had added, so they were on my local computer but not on github->heroku. I found this out by making a change only on sessions_helper, then committing to git only to get a message that there were no changes to any files but several (all of the sessions files) were untracked.
Happened because I used git -am "commit message" rather than git add -A first bc I thought the -a flag added everything. Should've checked git to make sure sessions_helper.rb was there, all the answers told me to check this but I was only checking on my local machine.
In my app I have a page that posts the statuses of users I follow. I'm new to rails and this error is killing me. I can give anything else if its needed
pages_controller.rb
def home
if signed_in?
#hub_items = current_user.hub.paginate(page: params[:page])
end
end
user.rb
def hub
Timeline.from_users_followed_by(self)
end
timeline.rb
def self.from_users_followed_by(user)
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
where("user_id IN (#{followed_user_ids}) OR user_id = :user_id",
user_id: user.id)
end
And this is the error trace.
Started GET "/" for 127.0.0.1 at 2014-08-24 14:11:28 -0700
Processing by PagesController#home as HTML
User Load (3.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
Completed 500 Internal Server Error in 257ms
NoMethodError (undefined method `where' for Timeline:Class):
app/models/timeline.rb:47:in `from_users_followed_by'
app/models/user.rb:24:in `hub'
app/controllers/pages_controller.rb:5:in `home'
Rendered C:/Ruby200/lib/ruby/gems/2.0.0/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.0ms)
Rendered C:/Ruby200/lib/ruby/gems/2.0.0/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)
Rendered C:/Ruby200/lib/ruby/gems/2.0.0/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (5.0ms)
Rendered C:/Ruby200/lib/ruby/gems/2.0.0/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (646.0ms)
class Timeline
def self.do_something
where(...) # is equivalent to self.where(...)
# The `where` method should in your app be defined by ActiveRecord,
# and present in those classes that inherit from ActiveRecord::Base
# (`class Post < ActiveRecord::Base; end). Since Timeline is no class
# backed by a database table, you will want to load `Post.where(...)
# or SomeModel.where(...) to display in your timeline.
end
end
you could also use scopes with params http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments