Checkboxes for has_many through, with additional join table attribute

520 views Asked by At

I have a has_many :through association between some models, which determine which datasets are visible on certain dashboards.

class Dashboard < ActiveRecord::Base
  has_many :dashboard_datasets
  has_many :datasets, :through => :dashboard_datasets
end

class DashboardDataaset < ActiveRecord::Base
  belongs_to :dashboard
  belongs_to :dataset
end

class Dataset < ActiveRecord::Base
  has_many :dashboard_datasets
  has_many :dashboards, :through => :dashboard_datasets
end

The form for creating a new Dashboard then has a simple set of checkboxes named dataset_ids[] to allow you to select which pre-existing datasets I want to be displayed on that dashboard.

class DashboardForm < Reform::Form
  model: :dashboard

  property :name
  property :description
  collection :dataset_ids
end

So far, so simple...

I'm now, however, looking to add an additional association to the join table, to determine the 'layout' which should be used for that dataset on that given dashboard. i.e. grid, table, list. etc

class Layout < ActiveRecord::Base
  has_many :dashboard_datasets
end

class DashboardDataaset < ActiveRecord::Base
  belongs_to :dashboard
  belongs_to :dataset
  belongs_to :layout
end

I now want to adapt my dashboard form, so that in addition to the checkboxes, for each dataset checkbox which is selected, there is a select box for me to choose the layout to be used on this given association.

Where do I begin? Expand the collection on the form object to be richer and include more information?

Greatly appreciate any advice.

1

There are 1 answers

0
Dave Benson On

Found a good example here by 0k32

The key pieces of information are:

  • Set up a standard has_many association, factory -> factory_color -> color
  • use accepts_nested_attributes_for on factory_color
  • Create a temporary model list, with a model for each checkbox. (factory.all_colors)
  • Use a fields_for feature where you can pass the association, and a separate list of the models e.g. fields_for :factory_colors, @factory.all_colors do |fc| ...
  • Add a before filter in the controller to set the _destroy attribute for unchecked items.