Rails - acts_as_list with multiple Models
Asked Answered
S

1

8

I've managed to use act_as_list with my Models (it was quite easy) one by one, but now i have a problem.

In my app there are 3 models: Facility, Service and Activity. I need to use acts_as_list on their union... is it possible to do that?

Hope my question is clear

Substage answered 13/6, 2011 at 11:46 Comment(0)
T
6

You should use a fourth model with a polymorphic association, then put the list on that.

First, read up on polymorphic associations to understand this: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Now you'll want to have a class that looks like this:

class Position < ActiveRecord::Base
  belongs_to :positionable, polymorphic: true
end

And a migration that looks like this:

class CreatePositions < ActiveRecord::Migration
  def change
    create_table :position do |t|
      t.integer :positionable_id
      t.string  :positionable_type
      t.timestamps
    end
  end
end

Then on each of the other models add this:

class Facility < ActiveRecord::Base
  has_one :position, as: :positionable
  # ...
end
Titfer answered 10/5, 2012 at 3:57 Comment(3)
Can you expand a little on the overall structure? Like have a Position model, with positionable_id. Then have the other three models have_one , :as positionable?Soothsayer
fyi, ryan bates just had a railscast on the topic: railscasts.com/episodes/154-polymorphic-association-revisedTitfer
Hey Jeff, yeah I saw that. Got it all sorted and working well thanks!Soothsayer

© 2022 - 2024 — McMap. All rights reserved.