Trisma
Trisma

Reputation: 765

Getting information from a rails class instance

I'm pretty new to Ruby and Rails so I'm sure this is really simple, but here is my thing.

I get request like this:

request = Request.where(id: params[:id_request])

So I logged this in console and it's returning what I want, but how do I access some fields of that?

I tried this:

request.required_people

This don't work obviously, but how do I get required_people from request?

Upvotes: 0

Views: 109

Answers (1)

Mark
Mark

Reputation: 6445

When you call where, you're returning a collection of items rather than an individual record, even if that where query only returns one result. As this collection is an instance of ActiveRecord::Relation we can call .first to get the first item in the collection:

request.first.required_people

But since you are looking for a single record you can just use .find which takes the model's primary key id as it's argument:

request = Request.find(params[:id_request])

That will let you do

request.required_people

If you really want to see the difference, try doing both the where and the find query. You'll see the where query has a few extra brackets on the return value.

Upvotes: 3

Related Questions