0

Undefined method errors when I try to use a column alias for an aggregate (PostgreSQL)

Inside my model:

class B2bLoginAttempt < ActiveRecord::Base
  set_table_name "b2b_logins"
end

Inside my controller:

    @client_ip = request.env['REMOTE_ADDR']
    @sql = "select count(id) as failed_logins FROM b2b_logins WHERE ip_address = '"+@client_ip+"'"

    f = B2bLoginAttempt.find_by_sql(@sql)
    failed_attempts = f.failed_logins.to_s
    f.destroy

Then I see: undefined method `failed_logins' for #<Array:0x104d08478>

0

2 Answers 2

2

The error occurs because find_by_sql returns an array, so you need to write f.first.failed_logins.to_s instead of f.failed_logins.to_s. Check find_by_sql doc here.

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure I am completely following your logic correctly, but it seems like you may be better off with this:

f = B2bLoginAttempt.where("ip_address = ?", @client_ip)

f.map(&:destroy)

You can get the actual count with f.count

Did I miss something?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.