Where to set up foreign key relationships in rails app with has_many through
I am setting u开发者_如何学编程p a simple has_many through relationship. I was wondering if there are any best practices I should consider when setting up the foreign key relationships.
The application is designed to allow users to create items and ads, where a listing model is used to connect items with ads (the listing model also has timestamps and an order field).
The main question I have is: which models should belong_to the user model? I was thinking that the simplest solution is to have listing belong_to user. That way I can use the has_many through relationship to figure out which items and which ads belong_to each user.
However, it occurred to me that this could leave some holes depending on what work-flows I want to make possible. For example, what if a user wants to create a bunch of items before creating an ad which has those items? What if a user creates an ad before having created any items?
Based on the above, I was thinking that maybe I should just make ads and items belong to user. If I do that, is there any obvious reason to also make listing belong_to user? I was going to do that, but somehow it just looked redundant to me.
This seems like a pretty typical situation to encounter in a rails app, so I was hoping somebody with experience has been here and might be able to share some insight.
Thanks!
I'm trying to understand what you have:
User Ad Item Listing
Where Listing
appears to be some kind of join model that relates an Item
to being in an Ad
.
I don't see much of a wrong way to do this. I suppose the most normalized way of doing this would be to just have an Item belong_to
a User, and get the Listings and Ads through that. But you'd be paying a price there too, both in having to write annoying code and having to perform multiple joins to get your Ads.
The opposite extreme is just to have everything belong_to
the user. You have an extra column in 2 of your models, but then you also have much simpler relationships. You also wouldn't have to worry about what workflows your users are allowed when designing your schema.
Even if you mess up and leave out user_id
fields in your models, it isn't terribly hard to add those fields later using migrations.
精彩评论