2

Are there any ways to use virtual attributes as conditions in Rails' finders?

For example:

Friend.find(:first, conditions: { full_name: 'Chandler Bing' })

Friend.where(login: 'chandler_bing@friends.tv', password: 'secret')

# `full_name' and `password' are virtual attributes

Thanks.

Shamaoke
  • 6,222
  • 8
  • 34
  • 40

3 Answers3

3

I use something like this in a recent project. I use it to select records that are in a certain date range. I do not use a finder but a scope.

scope :since, lambda {|from, to| {:conditions => {:created_at => (from .. to)}}}

This is then called like Model.since from, to where the created_at of Model field is checked against the range given.

To do this for virtual attributes you have to create the virtual field in your scope. Like match on first_name and last_name fields to create a match on full_name

Ben
  • 13,297
  • 4
  • 47
  • 68
1

What's a virtual attribute? An attribute not backed by database field?

Then you can't do that.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

Virtual attributes in general are not persisted in the database. They are calculated either during saving the record or after fetching the record from the database. You cannot do it then!

Arun Kumar Arjunan
  • 6,827
  • 32
  • 35