James Osborn
James Osborn

Reputation: 187

Rails 3: Find_or_create_by_name not saving

I'm trying to do a find_or_create_by function in my locations model. The attributes are saving but the find or create function isn't working. I have a name field and if I enter 'London', it is saving despite this value already being in the table.

Any suggestions why this may be?

EDIT: Added before_save invocation, as suggested by comment. - Still having the same problem.

Locations.rb

  class Location < ActiveRecord::Base
     before_save :location_check
     has_and_belongs_to_many :posts
     has_many :assets
     attr_accessible :latitude, :longitude, :name, :post_id, :notes, :asset, :assets_attributes
     accepts_nested_attributes_for :assets, :allow_destroy => true
     include Rails.application.routes.url_helpers


   def location_check
    def locations_attributes=(values)
    self.location = Location.find_or_create_by_name(values)
   end
 end  
end

EDIT: Here is the output log:

INSERT INTO "locations" ("created_at", "latitude", "longitude", "name", "notes", "post_id", "updated_at") VALUES (?, ?, ?, ?, ?, 
 ?, ?)  [["created_at", Wed, 14 Nov 2012 19:48:50 UTC +00:00], ["latitude", nil],    ["longitude", nil], ["name", "London"], ["notes", "notes"], ["p
 ost_id", nil], ["updated_at", Wed, 14 Nov 2012 19:48:50 UTC +00:00]] 

Upvotes: 0

Views: 408

Answers (2)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Based on the comments, I'd refactor it like this:

class Location < ActiveRecord::Base
   has_and_belongs_to_many :posts
   has_many :assets
   attr_accessible :latitude, :longitude, :name, :post_id, :notes, :asset, :assets_attributes
   accepts_nested_attributes_for :assets, :allow_destroy => true
   include Rails.application.routes.url_helpers

   validates :name, :uniqueness => true

end

Then in your controllers do:

loc = Location.find_or_create_by_name('London')

And if you forget and try to do:

loc = Location.create(:name => 'London')

and that record already exists, it will fail the uniqueness validation.

Upvotes: 1

lifejuggler
lifejuggler

Reputation: 460

could it be due to the case difference between what you had and the input entered? E.g: London and london

Upvotes: 0

Related Questions