Question

I'm building an app where a user can make a list of places they'd like to get the weather from.

So, I have a member model, a place model and a members_places table.

Member 
has_and_belongs_to_many :places, uniq => :true

Place
has_and_belongs_to_many :members, uniq => :true

I have a join table of members_places

In my places controller, I have

def create
    @member.places.create(params[:place])
    respond_with @member.places
end

When I run the create, I get duplicate key value violates constraint "index_places_on_name_and_lat_and_lon

I was hoping that has_and_belongs_to_many would use find_or_create_by, but I'm thinking it doesn't. Is there a way to get it to do this?

Was it helpful?

Solution

The answer wasn't too difficult, but a bit strange.

What I ended up doing was

def create
    @place = Place.find_or_create_by_name_and_lat_and_lon(params[:place])
    @member.places << @place
    respond_with @member.places
end

Worked right away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top