DonMB
DonMB

Reputation: 2718

activerecord: check first X chars of column

I'd like to check the first two chars of a number straight in my model. First I define the number of the current logged in user (devise):

user_number = current_user.number.first(2)

then I want to take that value and check it within a where statement in a "number" mobel, so I tried this

@numbers = Number.where(:number_value.first(2) => user_number)

which is obviously the same as

@numbers = Number.where(:number_value.first(2) => current_user.number.first(2))

No, that does not work.

How can I check the first 2 chars of the :number_value column in my model? Any help is appreciated.

Many thanks.

Upvotes: 0

Views: 58

Answers (2)

DonMB
DonMB

Reputation: 2718

Solution (SQLite)

@numbers = Number.where("number_value like '" + current_user.number.first(2) + "%'")

since this is not lazy loading I'm not convinced yet that it is the smartest solution. if you know any better, would be cool if you can share

Upvotes: 2

barelyknown
barelyknown

Reputation: 5560

First, you should read the ActiveRecord query guide. I'd also imagine that there's a much more straight forward way for you to accomplish your goal.

But, to answer your specific question, here's an approach that'd work with Postgresql.

Number.where("number_value::text like ?", current_user.number.to_s[0,2] + "%")

Upvotes: 1

Related Questions