0

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?

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.