Authlogic - how to check if a user is logged out - ruby

This is my setup:
user.rb
acts_as_authentic do |c|
c.logged_in_timeout(1.minutes)
end
user_session.rb
def to_key
new_record? ? nil : [ self.send(self.class.primary_key) ]
end
self.logout_on_timeout = true
application_controller.rb
helper_method :current_user_session, :current_user
private
def current_user_session
logger.debug "ApplicationController::current_user_session"
return #current_user_session if defined?(#current_user_session)
#current_user_session = UserSession.find
end
def current_user
logger.debug "ApplicationController::current_user"
return #current_user if defined?(#current_user)
#current_user = current_user_session && current_user_session.user
end
def require_user
logger.debug "ApplicationController::require_user"
unless current_user
#store_location
flash[:warning] = "You must be logged in to access this page"
#redirect_to new_user_session_url
redirect_to root_url
return false
end
end
def require_no_user
logger.debug "ApplicationController::require_no_user"
if current_user
#store_location
flash[:warning] = "You must be logged out to access this page"
redirect_to account_url
return false
end
end
But when I load my page, I will get the error
undefined method `logged_out?' for #<User:0x00000103ee8348>
I try to read the official GitHub page of Authlogic, but I still don't know, what I miss... Could anyone give me a tip for fix it?
Many thanks in advance!

I was having the exact same problem, and it boiled down to the fact I didn't have all of the necessary columns in my User model.
My original User model (from db/schema.rb) was pretty minimalistic:
create_table "users", :force => true do |t|
t.string "username"
t.string "name"
t.string "crypted_password"
t.string "password_salt"
t.string "persistence_token"
t.string "perm", :default => "employee"
end
However, I added the column t.datetime :last_requested_at to my model, as well as a few others that may or may not be needed. My final User model looks like:
create_table "users", :force => true do |t|
t.string "username"
t.string "name"
t.string "crypted_password"
t.string "password_salt"
t.string "persistence_token"
t.string "perm", :default => "employee"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "login_count", :default => 0, :null => false
t.integer "failed_login_count", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "current_login_at"
t.datetime "last_login_at"
t.string "current_login_ip"
t.string "last_login_ip"
end
After adding in the other columns, I no longer get the undefined method 'logged_out?'... error.
Good luck!
(reference/more info: http://www.michaelhamrah.com/blog/2009/05/authlogic-and-openid-on-rails/ -- search in the page for logged_out?, the explanation was about 3/4 of the way down the post.)

If you want to know if a user is logged out, you can do:
if current_user_session
...
This condition will return true if the user is logged in (there is a session), and false if they are logged out (the session is nil).
As for the error message, undefined method 'logged_out?' for #<User:0x00000103ee8348> means that you haven't defined a method called logged_out?, so it doesn't know what you mean.
Authlogic doesn't define a logged_out? method for the User model, and neither have you, so there's nothing to call. The reason is that the state of either being "logged in" or being "logged out" doesn't have anything to do with the User model, but instead is a property of whether or not a given user has an active UserSession record.

Related

Rake Setup - ActiveRecord::RecordInvalid: Validation failed:

In trying to run a setup rake tasks(to populate my dbase). It is telling me that questions must exist. When I do a count on 'Question.count' - it returns 4 - so I know questions exist.
What am I missing? typo? syntax? When I look at similiar SO, it shows as some sort of typo but I am not seeing it.
Here is the code that is not working:
def add_option_group
puts " * Add Option Groups...\n"
OptionGroup.transaction do
create_option_group(
option_group_name: "Always-Never",
question_id: Question.find_by(question_name: "Do you have an updated photo?")
)
create_option_group(
option_group_name: "Yes-No",
question_id: Question.find_by(question_name: "Do you have a bio saved (updated in last 12 months)?")
)
end
end
def create_option_group(options={ })
puts " * CREATE OptionGroup Section...\n"
option_group_attributes = {}
attributes = option_group_attributes.merge options
option_group = OptionGroup.create! attributes
option_group.save!
option_group
end
I am getting this error message:
Add Option Groups...
CREATE OptionGroup Section...
rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Questions must exist
/Users/axxx/workspace/fresh-assess/lib/tasks/setup.rake:314:in create_option_group' /Users/axxx/workspace/fresh-assess/lib/tasks/setup.rake:298:in block in add_option_group'
/Users/axxx/workspace/fresh-assess/lib/tasks/setup.rake:297:in add_option_group' /Users/axxx/workspace/fresh-assess/lib/tasks/setup.rake:51:in create_sample_data!
Migration files:
***** migrations ******
class CreateOptionGroups < ActiveRecord::Migration[6.1]
def change
create_table :option_groups do |t|
t.bigint :question_id
t.text :option_group_name
t.timestamps
end
end
end
class CreateQuestions < ActiveRecord::Migration[6.1]
def change
create_table :questions do |t|
t.bigint :assessment_section_id
t.bigint :input_type_id
t.text :question_name
t.string :question_subtext
t.boolean :question_required_yn
t.boolean :answer_required_yn
t.boolean :allow_multiple_options_answers_yn
t.integer :dependent_question_id
t.integer :dependent_question_option_id
t.integer :dependent_answer_id
t.timestamps
end
end
end
Here is schema
t.bigint "question_id"
t.bigint "option_choice_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "questions", force: :cascade do |t|
t.bigint "assessment_section_id"
t.bigint "input_type_id"
t.text "question_name"
t.string "question_subtext"
t.boolean "question_required_yn"
t.boolean "answer_required_yn"
t.boolean "allow_multiple_options_answers_yn"
t.integer "dependent_question_id"
t.integer "dependent_question_option_id"
t.integer "dependent_answer_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
Add foreign key:
class ForeignMoreKeysToModels < ActiveRecord::Migration[6.1]
def change
add_foreign_key :option_groups, :questions, validate: false
add_foreign_key :option_choices, :option_groups, validate: false
end
end
In the model:
class Question < ApplicationRecord
has_one :assessment_section
belongs_to :assessment_section, optional: true
has_many :option_groups
end
class OptionGroup < ApplicationRecord
has_many :option_choices
belongs_to :questions
end
What am I missing?
thx.
Two issues:
In the OptionGroup class, it should say belongs_to :question.
Try adding .id to the question lookup:
create_option_group(
option_group_name: "Always-Never",
question_id: Question.find_by(question_name: "Do you have an updated photo?").id
)

Creating an ActiveRecord database for a webcrawler. Having issues adding index

I'm working on a three part program for a webcrawler program for school. My first step is to just create the database using activerecord and knowing that it will be queried later using sqlite3. The database actually does get created with my current program. However, it errors out when gets to "add_index". I'm not great with databases in general so guidance is appreciated.
Before I put in my code the error is:
crawler_create.rb:23: syntax error, unexpected ',', expecting ')'
add_index (:pages,[:url], unique=> true)
Here's what I've come up with so far:
require 'active_record'
require 'sqlite3'
db=SQLite3::Database.new("crawler.db")
ActiveRecord::Base.establish_connection(adapter:'sqlite3',database:'crawler.db')
ActiveRecord::Schema.define do
create_table :pages do |t|
t.string :url, :null => false
t.string :title
t.string :content_type
t.date :last_modified
t.string :status
end
end
add_index (:pages,[:url], unique=> true)
ActiveRecord::Schema.define do
create_table :links do |t|
t.integer :from_page_id, :null => false
t.integer :to_page_id, :null => false
end
end
add_index(:links,[:from_page_id,:pages_id], :unique =>true)
ActiveRecord::Schema.define do
add_foreign_key :from_page_id, :pages_id
add_foreign_key :to_page_id,:pages_id
end
It looks like you got a simple syntax error here:
add_index (:pages, [:url], unique: true)
I'd suggest that you use a consistent hash syntax, either using hash rockets => or the newer syntax unique: true.

Ancestry gem gives error "The scope body needs to be callable." in rails 4?

models/message.rb
class Message < ActiveRecord::Base
has_ancestry
end
schema.rb
create_table "messages", force: :cascade do |t|
t.text "content"
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ancestry"
end
after adding has_ancestry in model it gives error Argument Error.
"The scope body needs to be callable."
Please help me
Thanks

How do I properly add a foreign key in active record?

I'm trying to create some referential integrity across several tables, and am tripping over the placement of add foreign keys. At best the statement is ignored, worst it throws an error.
class CreateCantons < ActiveRecord::Migration
def change
create_table :cantons do |t|
t.integer :canton_id
t.string :canton_name
t.timestamps null: false
end
end
end
class CreateResources < ActiveRecord::Migration
def change
create_table :resources do |t|
t.integer :resource_id
t.string :resource_name
t.integer :type_id
t.integer :canton_id
t.string :url
t.string :address
t.string :city
t.string :state
t.string :zip
add_foreign_key :cantons, :canton_id #ignored
add_foreign_key :types, :type_id #ignored
t.timestamps null: false
end
end
end
class CreateResourceContacts < ActiveRecord::Migration
def change
create_table :resource_contacts do |t|
t.integer :contact_id
t.integer :resource_id
add_foreign_key :resources, :resource_id
add_foreign_key :contacts, :contact_id
t.timestamps null: false
end
end
end
adding a t in front throws an error
t.add_foreign_key :contacts, :contact_id #error
How do I properly use this command?
you need to move the foreign_keys outside of the create table
class CreateResources < ActiveRecord::Migration
def change
create_table :resources do |t|
t.integer :resource_id
t.string :resource_name
t.integer :type_id
t.integer :canton_id
t.string :url
t.string :address
t.string :city
t.string :state
t.string :zip
t.timestamps null: false
end
add_foreign_key :resources, :cantons
add_foreign_key :resources, :types
end
end
see http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key
And also you need to tell it what tables you are adding it to.

Devise login validation failure

I rails3.0.4 and devise installed with following users table
create_table "users", :force => true do |t|
t.string "login"
t.string "email"
t.string "crypted_password", :null => false
t.string "password_salt", :null => false
t.string "persistence_token", :null => false
t.string "single_access_token", :null => false
t.string "perishable_token", :null => false
t.datetime "created_at"
t.datetime "updated_at"
t.string "database_authenticatable", :null => false
t.string "recoverable"
t.string "rememberable"
t.string "trackable"
t.string "reset_password_token"
end
The users table was not created by devise but I added the necessary
columns in migration.
And following settings in config/initializers/devise.rb
config.authentication_keys = [ :email]
But every time I try to sign up as a new user it throws:
2 errors prohibited this user from being saved:
Login is too short (minimum is 3 characters)
Login should use only letters, numbers, spaces, and .-_# please.
Any ideas why it could happen?
Yes, the login is too short and/or contains the wrong characters :)
You enabled the devise built-in validations, and that's what they validate. To use your own validations remove :validatable from your devise inclusion in app/models/user.rb
If you're interested, the validation used by devise is defined in lib/devise/models/validatable.rb in the devise gem.
Should the validation not be the problem you'll have to show the log of a user creation request, so that we can see what parameters are submitted.
EDIT: Oh I see, I misread - it's about "login". Well, see comments below.

Resources