Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what would happen if you use belongs_to without having a corresponding has_one?

I have a core model for an Item, and a script to populate it from a custom source (think, RSS feed). In the feed, each Item is identified with a guid; in my system, Item only has an autogenerated id primary key.

I want to have, let's say, ItemFeedInfo that maps guid->id (so that I can distinguish between new vs. modified Items)

I'm thinking of creating

class ItemFeedInfo
  belongs_to :Item
end

I would prefer not to modify Item since its definition is logically independent of ItemFeedInfo However, every example I can find of using belongs_to, mentions a has_one counterpart. Is it required?

like image 334
ykaganovich Avatar asked Mar 30 '09 20:03

ykaganovich


1 Answers

It doesn't matter.

belongs_to simply adds some methods to the ItemFeedInfo class. You know when you do item_feed_info.items.find_all... The items is just a method which got dynamically added when you called belongs_to.

If you don't modify the Item class, then you simply won't be adding the methods on the other side. You won't be able to do item.item_feed_infos.find_all, because without adding has_many :item_feed_infos, that method won't have been added to the Item class, but if you never actually need to do this, it won't matter.

like image 93
Orion Edwards Avatar answered Nov 15 '22 15:11

Orion Edwards