简体   繁体   中英

Iterating through IDs Ruby on Rails

I have been advised not to store arrays in my DB, but instead just IDs. In my project, I am storing IDs for line-items. If I don't have a line_item OBJECT, but only IDs, could I still iterate through a loop to get all of the data associated with it?

To explain further...

Traditionally I feel like I have

@line_item
>> <LineItem id: 63, product_id: 2, created_at: time, (etc) >

Then I could do something like

@line_item.title
>> "T-Shirt:Small"

But what if I did

@line_item

and got

>>[12, 14]

Could I do a @line.item.each and get to all the information I need from the just the IDs in the view?? or would I have to create my own scary method?

Hopefully I've posed my question understandably.

Thanks.

You can do this:

@items = [12,14]  # your list of ids you got from somewhere
@items.each do |id|
   @line_item = LineItem.find(id)  # Get the instance for that id.
   # do stuff.
end

You could also do something like this:

@line_items = LineItem.find(@id_list)

If the reason you are storing lists of ids is to capture relationships then you should look at the belongs_to and has_many relationships that rails provides. De-normalising data by storing lists is nasty because you don't know how long your list will be. It stops your database from indexing things properly and it's hard to maintain.

I suggest you to use:

LineItem.where(id: [12,14])

As it will return always an array of items. If you try to find for an item who's not in the database you will find a record not found error. This will render an empty array in case no record is found.

As long as you have an array, empty or not, you won't have to rescue the .each method because it won't fail in any case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM