Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a model by its referenced model (child?) in Ruby on Rails

Rails nooby here, looking for some tips. I've looked around on the site and the Rails website and can't seem to find what I'm looking for.

I have an account class

class Account < ActiveRecord::Base
  has_one :access_token, dependent: :destroy
  has_secure_password

and of course

class AccessToken < ActiveRecord::Base

What I want to be able to do in my controllers is Account.find_by_access_token or something like that. Is there a way to do this in Rails?

like image 484
Csteele5 Avatar asked Jan 20 '26 02:01

Csteele5


1 Answers

Assuming the column's name is AccessToken is named token, try:

class Account < ActiveRecord::Base
  def self.find_by_token(token)
    Account.joins(:access_token).where(access_tokens: { token: token } )
  end
end

And then use it like this:

Account.find_by_token('XXXXXXX')
like image 165
dgilperez Avatar answered Jan 21 '26 16:01

dgilperez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!