Mark Davies
Mark Davies

Reputation: 796

Creating a ruby object from multiple models

I am trying to create an object from several models which I can return using an active record query. The aim being to use the results to create a CSV output file from a subsequent query.

Lets say I have a simple model of items which have a status. The status is held with the ID as you would do in a normalised database. An item would have many statuses and a status would belong to an item (to achieve the relationship).

I've put some data in to illustrate this:

Item (model)
============
id    status_id
---------------
1     1
2     2
3     3

Status
============
id    title
---------------
1     Available
2     Loaned
3     Missing

Basically I want to be able to return the data as follows in an object:

item_id    status_title
--------------------
1          Available
2          Loaned
3          Missing

I know I could achieve this using a "find by sql", however I was hoping this could be returned using active record and relationships.

I've had a look at trying to use delegate but couldn't get that to work (assuming that it would do what I need).

Anyone advise on if this is possible?

Upvotes: 0

Views: 34

Answers (1)

Maxim
Maxim

Reputation: 9981

You should declare belongs_to association:

class Item
    belongs_to :status
end

and use it in AR query:

Item.joins(:status).select('items.id as id, statuses.title as status_title')

Upvotes: 1

Related Questions