我正在尝试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]]