Best way to associate profiles with multiple banners
I am looking to create an app that will allow me to associate multiple profile images with multiple ads.
I believe this will be a has_and_belongs_to_many association as I want an ad to have multiple profiles and profiles can belong to multiple ads. I am however slightly confused as to how this will work with my database tables.
If an ad has a single row in my ads table then how will it associate multiple profile images (stored in my profiles table) in a single profile_id cell? Do i need to setup a seperate third model and database table to handle those that are associated?
I am also confused whether it is essential to set up nested resources to get HABTM associations to work successfully - at the moment I have them seperated as so:
resources :ads resources :profiles
Sorry for the basic question but I can't seem to find any information that helps my issue and the rails guide on HABTM associations is pretty short.
Thanks in advance for any help you can offer! :)
You do not need nested resources to get "it to work." You do need another table that connects your models together named ads_profiles (plural and in alphabetical order by convention). The table contains two columns (ad_id and profile_id). With an ad object you can get profiles (ad.profiles) and with a profile get the ads (profile.ads).
This will get you started: http://guides.rubyonrails.org/association_basics.html
When you create a HABTM association, you have to manually create the association table. In your case is ads_profiles.
rails g migration create_table_ads_profiles
This table will contain ad_id and profile_id, where you can now have multiple records associated. One more gotcha, on the migration, don't forget to add a :id => false to it
class CreateTableAdsProfiles < ActiveRecord::Migration def change create_table :ads_profiles, :id => false do |t| t.integer :ad_id t.integer :profile_id end end end
If you have further questions, fell free to ask.