Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created September 13, 2013 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/6548302 to your computer and use it in GitHub Desktop.
Save zmajstor/6548302 to your computer and use it in GitHub Desktop.
Rails 4 sample for grouping Devices into DeviceGroups (form_for ActiveRecord has_many :through Association)
class DeviceGroupsController < ApplicationController
# ...
private
def device_group_params
params.require(:device_group).permit(:title, {:group_ids => []} )
end
# ...
end
<%= form_for(@device_group) do |f| %>
...
<div class="field">
<%= f.label "Check group members:" %>:<br />
<%= hidden_field_tag "device_group[device_ids][]", nil %>
<% Device.all.each do |device| %>
<%= check_box_tag "device_group[device_ids][]", device.id, @device_group.device_ids.include?(device.id), id: dom_id(device) %>
<%= label_tag dom_id(device), device.name %>
<% end %>
</div>
...
<% end %>
class Device < ActiveRecord::Base
has_many :device_groupings, :dependent => :destroy
has_many :device_groups, :through => :device_groupings
end
class DeviceGroup < ActiveRecord::Base
has_many :device_groupings, :dependent => :destroy
has_many :devices, :through => :device_groupings
end
class DeviceGrouping < ActiveRecord::Base
belongs_to :device_group
belongs_to :device
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment