Skip to content

Instantly share code, notes, and snippets.

@chocnut
Created December 31, 2011 01:51
Show Gist options
  • Save chocnut/1542436 to your computer and use it in GitHub Desktop.
Save chocnut/1542436 to your computer and use it in GitHub Desktop.
has_many problem :)
Models
class User < ActiveRecord::Base
has_many :dnshospitals
has_many :hospitals, :through => :dnshospitals
end
class Hospital < ActiveRecord::Base
has_many :dnshospitals
has_many :users, :through => :dnshospitals
validates_presence_of :name, :abbreviation, :city
end
class Dnshospital < ActiveRecord::Base
belongs_to :user
belongs_to :hospital
end
Controller
class DnshospitalsController < ApplicationController
def new
@dns = current_user.dnshospitals.build
end
def create
@dns = current_user.dnshospitals.build(params[:dnshospital])
if @dns.save
flash[:notice] = "DNS added successfully"
redirect_to user_profile_path + "#tabs-DNS"
else
flash[:alert] = "Please fill up the required fields"
render :action => 'new'
end
end
Views
_form.html.haml
= form_for([current_user, @dns]) do |f|
= render 'shared/flash_messages'
%p
%br/
= hidden_field_tag "dnshospital[hospital_ids][]", nil
- Hospital.all.each do |h|
= check_box_tag "dnshospital[hospital_ids][]", h.id, current_user.hospital_ids.include?(h.id), id: dom_id(h)
= label_tag dom_id(h), h.name
%br/
%p
= f.submit 'Add DNS', :class => "btn btn-green"
.clear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment