rails undefined method `attr_accessible' - ruby-on-rails

I'm trying to add an authentication system into my app and I've run into this error when I run "rake db:migrate":
NoMethodError: undefined method `attr_accessible' for User (call 'User.connection' to establish a connection):Class
/Users/liferaymac/Desktop/check/app/models/user.rb:8:in `<class:User>'
/Users/liferaymac/Desktop/check/app/models/user.rb:1:in `<top (required)>'
/Users/liferaymac/Desktop/check/config/routes.rb:2:in `block in <top (required)>'
/Users/liferaymac/Desktop/check/config/routes.rb:1:in `<top (required)>'
/Users/liferaymac/Desktop/check/config/environment.rb:5:in `<top (required)>'
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)
Here is a view of my user.rb file, which is my model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
end
And here is my migrate file:
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
# t.confirmable
t.recoverable
t.rememberable
t.trackable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
t.timestamps
end
add_index :users, :email, :unique => true
# add_index :users, :confirmation_token, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end
def self.down
drop_table :users
end
end
# migration
create_table(:users) do |t|
t.database_authenticatable :null => false
# t.confirmable
t.recoverable
t.rememberable
t.trackable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
t.timestamps
end
add_index :users, :email, :unique => true
# add_index :users, :confirmation_token, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :unlock_token, :unique => true
I'm working from http://railscasts.com/episodes/209-introducing-devise?autoplay=true
I also ran bundle install and installed the devise gem already.
Any insight will be greatly appreciated.

From the Rails Guides:
Rails 4.0 has removed attr_accessible and attr_protected feature in
favor of Strong Parameters. You can use the Protected Attributes gem
for a smooth upgrade path.
Source: http://guides.rubyonrails.org/upgrading_ruby_on_rails.html
You will probably want to keep the attr_accessible method or you will run into errors when creating users with a sign up form. You can bundle the protected_attributes gem to give you access to those methods in your models.
Protected Attributes: https://github.com/rails/protected_attributes

I realized that in Rails 4+ there is no "attr_accessible". I deleted it out of my model and now it works. (Should have expected this from an old video....)

Related

Rails error on migration, rake aborted

I have this migration to the table users made with Devise, all worked fine until i tried to make a back office with active_admin gem and added a role, etc:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :username, null: false, default: ""
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :username, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
And this migration that add a column to the table:
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :string
User.create! do |u|
u.username = 'admin'
u.email = 'admin#example.com'
u.password = 'admin123'
u.role = 'administrator'
end
end
end
I do rake db:migrate and got this error:
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
Record invalido/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord- 4.2.1/lib/active_record/validations.rb:79:in `raise_record_invalid'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/validations.rb:43:in `save!'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/attribute_methods/dirty.rb:29:in `save!'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/transactions.rb:291:in `block in save!'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord- 4.2.1/lib/active_record/transactions.rb:347:in `block in with_transaction_returning_status'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/transactions.rb:220:in `transaction'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/transactions.rb:344:in `with_transaction_returning_status'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/transactions.rb:291:in `save!'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/persistence.rb:51:in `create!' /home/dev8/RedTwitter/db/migrate/20150605140226_add_role_to_users.rb:6:in `change'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/migration.rb:606:in `exec_migration'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/migration.rb:590:in `block (2 levels) in migrate'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/migration.rb:589:in `block in migrate'
/home/dev8/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
........
I tried rake db:rollback and got a similar error.
What could it be?
EDIT:
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :registerable, :confirmable, :authentication_keys => [:login]
attr_accessor :login
has_many :tweets , dependent: :destroy
validates :username,
:presence => true,
:uniqueness => {
:case_sensitive => false
}, length: { in: 6..20 }
def role?(role)
roles.include? role.to_s
end
def login=(login)
#login = login
end
def login
#login || self.username || self.email
end
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_hash).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions.to_hash).first
end
end
end
I believe you need to call User.reset_column_information in your migration, after adding the new column, otherwise Rails doesn't know about it.
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :string
User.reset_column_information
u = User.new
u.username = 'admin'
u.email = 'admin#example.com'
u.password = 'admin123'
u.role = 'administrator'
u.save(:validate => false)
end
end
Use find or create method. This will allow you to not raise invalid record error if you already have user, so all later migrations will run well.

Confirmation email with devise gem in Ruby on Rails 4 - Error:undefined local variable or method `confirmed_at' for #<User:0x007fa52bb0ea50>

I have followed the steps in https://github.com/plataformatec/devise/wiki/How-To%3a-Add-%3aconfirmable-to-Users however I receive the error: NameError in Devise::RegistrationsController#create undefined local variable or method `confirmed_at' for # when i submit the signup form. How would I go about creating a confirmation email with the devise gem in Ruby on Rails 4? As well as what other requirements are needed? Here is what my code currently looks like:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins
validates :name, presence: true
validates :email, format: { with: /\A([^#\s]+)#((?:[-a-z0-9]+\.)+edu)\z/ }
end
class AddConfirmableToDevise < ActiveRecord::Migration
def change
change_table(:users) do |t|
t.confirmable
end
add_index :users, :confirmation_token, :unique => true
end
def self.up
add_column :users, :confirmation_token, :string
add_column :users, :confirmed_at, :datetime
add_column :users, :confirmation_sent_at, :datetime
# add_column :users, :unconfirmed_email, :string # Only if using reconfirmable
add_index :users, :confirmation_token, :unique => true
# User.reset_column_information # Need for some types of updates, but not for update_all.
# To avoid a short time window between running the migration and updating all existing
# users as confirmed, do the following
User.update_all(:confirmed_at => Time.now)
# All existing user accounts should be able to log in after this.
end
def self.down
remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
# remove_columns :users, :unconfirmed_email # Only if using reconfirmable
end
end
Did you make the necessary migrations to add confirmable module to User?
Devise Confirmable Wiki
Edit: I edited your Rails migration to this:
class AddConfirmableToDevise < ActiveRecord::Migration
def up
add_column :users, :confirmation_token, :string
add_column :users, :confirmed_at, :datetime
add_column :users, :confirmation_sent_at, :datetime
# add_column :users, :unconfirmed_email, :string # Only if using reconfirmable
add_index :users, :confirmation_token, :unique => true
# User.reset_column_information # Need for some types of updates, but not for update_all.
# To avoid a short time window between running the migration and updating all existing
# users as confirmed, do the following
User.update_all(:confirmed_at => Time.now)
# All existing user accounts should be able to log in after this.
end
def down
remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
# remove_columns :users, :unconfirmed_email # Only if using reconfirmable
end
end

devise forgot password setup

I am really new to rails and have been trying to work on building an application. I recently have installed devise and omniauth for facebook with great success after some time. When I was reading into devise, I noticed that Devise has a "forgot password" module built into it.
I have scoured the internet and for the life of me haven't figured out how to set it up. Is there any guide?I have been working for hours, but I haven't really had any results. How do I set this up? I am using rails 4.0 and the newest version of devise.
Thanks,
Routes
Omrails::Application.routes.draw do
resources :boards
resources :pins
get 'about' => "pages#about"
root :to => 'pins#index'
resources :tests, :birthdays
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
end
Devise Migration:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0, :null => false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end
end
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:registerable,
:rememberable,
:trackable,
:recoverable,
:validatable,
:omniauthable,
:omniauth_providers => [:facebook]
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :birthday, :sex, :address, :mobile, :provider, :uid
has_many :pins, :dependent => :destroy
has_many :boards, :dependent => :destroy
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
password:Devise.friendly_token[0,20])
end
user
end
end
Devise consists of 10 modules and the one you're looking for is recoverable. In your devise model, you need to add :recoverable attribute for devise.

Devise with OpenID in Rails3 beta4 but raise [undefined method `apply_schema'] error

I have use devise_openid_authenticatable to support OpenID with devise in rails3 beta4.
But when I run rake db:migrate, it occurs [undefined method `apply_schema'] error.like this:
== DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
rake aborted!
An error has occurred, all later migrations canceled:
undefined method `apply_schema' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x1036ffb40>
Here is my migration file:
class DeviseCreateUsers false
t.openid_authenticatable
t.recoverable
t.rememberable
t.trackable
# t.confirmable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
# t.token_authenticatable
t.timestamps
end
add_index :users, :identity_url, :unique => true
# add_index :users, :email, :unique => true
# add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end
def self.down
drop_table :users
end
end
And config.middleware.use Rack::OpenID in config/application.rb
Does anyone can give me a hand? Thank you!
I'm the author of devise_openid_authenticatable. This issue was caused by a change in API in Devise 1.1.0 stable. I've added code to check for this and choose the appropriate API to use. The fix is released in the new devise_openid_authenticatable 1.0.0.alpha3.
Sorry about the trouble!
I think I have fixed this problem.
First,type $ bundle show devise_openid_authenticatable to see where the bundled gem is installed.
e.g. /Users/YOURNAME/.bundle/ruby/1.8/gems/devise_openid_authenticatable-1.0.0.alpha2
cd in this directory and modify /lib/devise_openid_authenticatable/schema.rb
from apply_schema :identity_url, String to apply_devise_schema :identity_url, String
That's OK!

Devise registration confirmation

I have a User and an Admin role in my project. I created my authentication with Devise.
In my admin role I don't have any confirmation. In my User model I have the following:
devise :database_authenticatable, :confirmable, :recoverable,
:rememberable, :trackable, :validatable, :timeoutable, :registerable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :prename, :surname, :phone, :street, :number, :location,
:password, :password_confirmation
My migration looks like:
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
t.confirmable
t.recoverable
t.rememberable
t.trackable
t.timeoutable
t.validateable
t.string :username
t.string :prename
t.string :surname
t.string :phone
t.string :street
t.integer :number
t.string :location
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :confirmation_token, :unique => true
add_index :users, :reset_password_token, :unique => true
add_index :users, :username, :unique => true
add_index :users, :prename, :unique => false
add_index :users, :surname, :unique => false
add_index :users, :phone, :unique => false
add_index :users, :street, :unique => false
add_index :users, :number, :unique => false
add_index :users, :location, :unique => false
end
def self.down
drop_table :users
end
end
In my routes.rb I added following statements:
map.devise_for :admins
map.devise_for :users, :path_names => { :sign_up => "register", :sign_in => "login" }
map.root :controller => "main"
After user registration I am redirected to the controller main with the flash notice, "You have signed up successfully," and I am logged in. But I don´t want to be logged in, because I have not confirmed my new user account yet.
If I open the console I see in the logs the confirmation mail text, but I am already logged in. I can´t explain why. Does anyone have an idea?
If I copy out the confirmation-token from the logs and confirm my account, I can log in, but if I don´t confirm, I also can log in.
In config/initializers/devise.rb there is a line to set the amount of time a user has to confirm before they're locked out.
config.confirm_within = 2.days
If you set that to 0, you should get the desired outcome.

Resources