Reputation: 187
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.
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
Upvotes: 1
Views: 1202
Reputation: 163
in rails 4 this worked perfectly. Thanks to all.
def locations_attributes=(value)
self.location = Location.find_or_create_by(value)
end
This checks uniqueness across all attributes passed in for location.
Upvotes: 0
Reputation: 1034
try using:
def locations_attributes=(value)
self.location = Location.find_or_create_by_name(value)
end
Upvotes: 1