Search code examples
ruby-on-railshas-many

How to add invalid records to has_many :through association


I have a house model with a has_many-association for rooms.

house = House.find 1
dining_room = Room.find 1
living_room = Room.find 2

The living_room is not a valid dataset. So if I add the rooms to the house

house << dining_room
house << living_room

the living_room wasn't added, because it's invalid.

How can I skip the validation when adding an existing record to a has_many-association?


Solution

  • you can try something like this to associate a Room object to a House object skipping validation:

    declare something like this in room.rb

    def associate_room_to_house!(house)
      self.house_id = house.id
      self.save(:validate => false)
    end
    

    and then use this method on your invalid room object.

    house = House.find 1
    living_room = Room.find 2
    
    living_room.associate_room_to_house!(house)