1

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

4

2 回答 2

1

尝试使用:

def locations_attributes=(value)
  self.location = Location.find_or_create_by_name(value)
end
于 2012-11-04T15:52:17.123 回答
0

在rails 4中,这非常有效。谢谢大家。

def locations_attributes=(value)
  self.location = Location.find_or_create_by(value)
end

这将检查为位置传递的所有属性的唯一性。

于 2013-12-13T15:03:30.283 回答