Created
November 14, 2011 03:25
-
-
Save jkongie/1363163 to your computer and use it in GitHub Desktop.
has many :through nested attributes with checkboxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using formtastic but can easily converted to use standard rails form helpers | |
= semantic_form_for [ @user ] do |f| | |
= f.semantic_fields_for :user_specialities do |user_speciality| | |
= user_speciality.inputs do | |
= user_speciality.input :speciality_id, :as => :hidden | |
= user_speciality.input :_destroy, :label => user_speciality.object.speciality.name, :as => :boolean, :checked_value => 0, :unchecked_value => 1, :input_html => { checked: !user_speciality.object.new_record? } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# user.rb | |
class User < ActiveRecord::Base | |
has_many :user_specialities, :dependent => :destroy | |
has_many :specialities, :through => :user_specialities | |
attr_accessible :user_specialities_attributes | |
accepts_nested_attributes_for :user_specialities, :allow_destroy => true | |
end | |
# specialities.rb | |
class Specialities < ActiveRecord::Base | |
has_many :user_specialities, :dependent => :destroy | |
has_many :specialities, :through => :user_specialities | |
end | |
# user_specialities.rb | |
class UserSpecialities < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :speciality | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserController < ApplicationController | |
def edit | |
@user = current_user | |
build_unpicked_specialities | |
end | |
def update | |
@user = current_user | |
@user.update_attributes(params[:user]) | |
respond_with @user | |
end | |
private | |
# Builds and sorts unpicked specialities for a user to be used in the nested attribute | |
# Returns an array of user specialities sorted by speciality position | |
def build_unpicked_specialities | |
(Speciality.all - @user.specialities).each do |speciality| | |
@user.user_specialities.build(:speciality => speciality) | |
end | |
@user.user_specialities.sort_by! {|us| us.speciality.position } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment