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! :)

Answers


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

~Charles~


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.


Need Your Help

Trying to understand recursion within for loops in javascript

javascript for-loop recursion

I've been staring at the answer to this question forever even writing down variables and whatnot through each iteration. I simply just don't get the process here. When I throw in console logs I see

Problems returning a value while using a trait and companion object in Scala (Eclipse IDE)

scala main traits companion-object

I've placed the following code into an object.Scala file within Eclipse, and simply want to know what the value for "x" is (it should be 3). The code won't compile if I place the value anywhere other