omninonsense
omninonsense

Reputation: 6892

Is it possible to use a serialized property for associations?

I have something similar to this:

class Bucket < ActiveRecord::Base
  serialize :droplets, Array #of IDs
end

class Droplet < ActiveRecord::Base
  #...
end

Since a single Droplet can belong to multiple Buckets (the real problem is a bit more complex), is there a "rails-way" of achieving something similar to the following:

#in some action
@bucket = Bucket.find(47)
@droplets = Droplet.find_all_by_id(@bucket.droplets)

so that one can access Bucket#droplets where every element of the array would be a Droplet?

Upvotes: 0

Views: 56

Answers (1)

rik.vanmechelen
rik.vanmechelen

Reputation: 1914

It sounds like you want a many to many relationship. It is really recommended to do this with 3 tables. if you dont want this, you have to keep the array in the sql, in which case you will lose some rails functionality and have to do it as you described yourself with

@bucket = Bucket.find(47)
@droplets = Droplet.find_all_by_id(@bucket.droplets)

if you want to do in a cleaner way do:

class Bucket < ActiveRecord::Base
  has_and_belongs_to_many :droplets
end

class Droplet < ActiveRecord::Base
  has_and_belongs_to_many :buckets
end

you will need a migration:

# in migration
def change
  create_table 'buckets_droplets', :id => false do |t|
    t.column :bucket_id, :integer
    t.column :droplet_id, :integer
  end
end

Upvotes: 1

Related Questions