0

我正在尝试find_or_create_by在我的位置模型中执行一项功能。属性正在保存,但查找或创建功能不起作用。我有一个name字段,如果我输入'London',尽管该值已经在表中,但它正在保存。

任何建议为什么会这样?

编辑:添加了 before_save 调用,如评论所建议的那样。- 仍然有同样的问题。

地点.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

编辑:这是输出日志:

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]] 
4

2 回答 2

1

根据评论,我会这样重构它:

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

结尾

然后在您的控制器中执行以下操作:

loc = Location.find_or_create_by_name('London')

如果您忘记并尝试这样做:

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

并且该记录已经存在,它将无法通过唯一性验证。

于 2012-11-14T20:01:37.420 回答
0

可能是由于您所拥有的内容与输入的输入之间的大小写不同吗?例如:伦敦和伦敦

于 2012-11-14T19:18:21.637 回答