PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to add invalid records to has_many :through association

 October 21, 2022     has-many, ruby-on-rails     No comments   

Issue

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)


Answered By - sa77
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing