How to Find a Record in ActiveRecord Using either an ID Or an Object

Have you ever written written code in an ActiveRecord model where you wanted the caller to be able to pass in either an object or an id?

In this example you want to know if a user has read a post. Your join table, readings, tells you which users have read each post.

class Post
  has_many :readings

  def read_by?(user_or_id)
    readings.where(:id =>
                     Fixnum === user_or_id ?
                     user_or_id :
                     user_or_id.id).exists?
  end
end

Good news: you don’t have to go through all that. ActiveRecord checks for you if the object is a number or a model. You can simplify the code quite a bit.

In this rewritten version the user parameter of the read_by? method can be either a user object or a user id:

class Post
  has_many :readings

  def read_by?(user)
    readings.where(:id => user).exists?
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *

Feel free to use <a>, <b>, <i>, <strong>, <em>, <strike>, <code>.

Code blocks:
[code language="ruby/javascript/html/css/sass/bash"]
[/code]