Create a gist now

Instantly share code, notes, and snippets.

<%= f.text_field :pending_room_number, :value => @student.room_number %>
<%= f.collection_select :residence_id, Residence.all, :id, :name %>
class Room < ActiveRecord::Base
belongs_to :residence
has_many :students
end
class Student < ActiveRecord::Base
belongs_to :room
delegate :number, :residence, :to => :room, :prefix => true, :allow_nil => true
attr_accessor :pending_room_number, :residence_id
before_save :assign_room
def assign_room
self.room = if room = Room.find_by_number_and_residence_id(pending_room_number, residence_id)
room
else
Room.create! { :number => pending_room_number, :residence_id => residence_id}
end unless self.room.present?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment