Huw
Huw

Reputation: 645

Rails: Get a model to name itself

I have three models, houses, users & rooms.

Rooms is a pretty boring model, it is mainly used to designate which room a user occupies within a house. Aside from associations it only has one record, name. Name is it's boring designation that the user can set eg. "funky smelling attic room" or just boring old "Room 1".

If the user doesn't attribute a name (and if the room doesn't have any occupants for me to do some smarter auto-naming), I want the model to name itself.

Specifically I want it to do: Room #{i} (eg Room 1, Room 320, Room 12321) whenever the user calls Room.new() without attributes.

The bit I'm having trouble with is how t make it so that i connected to the associated house. So there could be many called 'Room 1' but they would all have to be in different houses, within each house the Room #{i} would need to be a unique name...

I know to do some of this with validations (uniqueness) but how... and where, would I put an enumerator to count up the number of rooms already present in a house and do i += 1 when it comes around to naming any new additions?

Upvotes: 0

Views: 52

Answers (1)

QuillyT
QuillyT

Reputation: 77

An option would be to create an after_create callback in your Room model:

class Room < ActiveRecord::Base
  belongs_to :house
  after_create :name_room

  def name_room
    if name.blank?
      update_column(:name, default_name)
    end
  end

  def default_name
    "Room #{rooms_in_house} of house #{self.house.id}"
  end

  def rooms_in_house
    self.house.rooms.count
  end
end

Hopefully I understood your question and gave you something useful... but it looks like you might not even have to use the enumerable count block!

If number of rooms isn't correct then you can adjust it in rooms_in_house by just adding 1 in the method.

Upvotes: 1

Related Questions