I have a challenge that I have been struggling to tackle for the last few hours.
I have a form with nested attributes. Each Post has and belongs to many Locations. I need each Location to be unique but I also need to be able to add the same location to many posts. Ideally this validation would be done within the model.
- So, in my posts form what currently happens is a user 'adds a location', they then search the foursquare API for a location.
- Upon submit this is saved into the Locations table with the location name and the longitude and latitude, there is a Locations_Posts table which ties these together.
- What needs to happen is the posts model should check if a location exists, if it does, don't add anything to Locations, just add the relevant data to the Locations_Posts table.
After some research I have worked out that I need something like this:
*Posts.rb*
# =================
# = Location validations =
# = If location exists then just add to locations_posts, else create new location =
def locations_attributes
location && location.name
end
def locations_attributes=(value)
self.location = Location.find_by_name(value)
self.location ||= Location.new(:name => value)
end
(Stolen from rails: create Parent, if doesn't exist, whilte creating child record)
However, I'm getting errors such as:
Unknown key: 0
I think I must be close with this snippet but need some help to get over the last hurdle!
Thanks in advance,
James