Andrew Lank
Andrew Lank

Reputation: 1617

rails find by path

Maybe I'm not searching on the right keywords but: Is it possible to search given an object path?

I have '/businesses/2' and I'd simply like to do something like @object = Business.find('/businesses/2') to fetch that object

One way is to:

ids = params[:who_id].split('/')
@object = ids[1].singularize.constantize.find(ids[2])

But I'm wondering if there is a built in way since this seemed to me as something quite normal to do.

Upvotes: 0

Views: 434

Answers (1)

socjopata
socjopata

Reputation: 5095

If you know that the id will be the last in the string then you can split the string by "/" and take the last element. If you're unsure, you may use regexp.

If you want also to perform a search depending on what's in your string (you do not know class name)) then use regexp to match a model name and then use these helpers: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html to get a name of the class.

Like:

klass = _yor_extracted_string.singularize.constantize
object = klass.find(_id_here_)

Upvotes: 1

Related Questions