views:

104

answers:

2

I'm building a site that has user defined pages that are composed of a set of widgets.

The widgets are fairly basic, similar to what you'd find in Blogger. Some widgets are for data collection/formatting presentation with basic structure (lists, tables) and others provide more complex functionality (blog, photo albums, etc)

I want to allow the user to select which widgets appear on their page and reorder them.

I was considering having Widgets be a STI (e.g. BlogWidget, GalleryWidget) and each Widget instance would have a fkey user_id and a position for sorting.

Then the user's show.html.erb would contain:

for widget in current_user.widgets
    render widget
end

Is there a better way?

A: 

I would create two models, "Widgets" and "UserWidgets", which would look as follows:

Widgets:
  ID (Primary Key)
  Name
  Description
  etc...

UserWidgets:
  ID
  Position
  Widget_ID (Foreign Key -> Widgets.ID)
  User_ID (Foreign Key -> Users.ID)

Set up the proper associations so you can simply do @user.widgets to get a list of all widgets. If you name your widgets the same as the name they have in the database, you could simply do the following in a view/layout/partial:

<% @user.widgets do |w| %>
  <%= javascript_include_tag w.name %>
<% end %>

This is of course assuming that you seperate each widget into it's own self contained JavaScript file (which would be my preferred method of doing it).

Mike Trpcic
Yep, that's a better description of what I was asking. Can anyone provide a better solution?
ABCoder
I think that IS the best solution.
Mike Trpcic
A: 

I ended up implementing it something like this:

class Placement < ActiveRecord::Base
  belongs_to :widget, :polymorphic => true
  belongs_to :container, :polymorphic => true

  acts_as_double_polymorphic_join(
 :widgets =>[:blogs, :galleries, :twitter_feeds], 
 :containers => [:pages, :users, :groups]
  )

  acts_as_list :scope => :container
end
ABCoder