【发布时间】:2012-11-14 18:59:18
【问题描述】:
我正在尝试在我的位置模型中执行 find_or_create_by 函数。属性正在保存,但 find 或 create 功能不起作用。我有一个 name 字段,如果我输入 'London',尽管这个值已经在表中,但它正在保存。
有什么建议吗?
编辑:添加 before_save 调用,如评论所建议的那样。 - 仍然有同样的问题。
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
编辑:这是输出日志:
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]]
【问题讨论】:
-
嗨菲尔,感谢您的评论。我不确定是否需要调用。我已经对此进行了修改,但没有任何变化。还有其他建议吗?
-
你试过
Location.find_or_create_by_name(name: values) -
感谢 Kien,但此更改没有任何区别。该条目只是保存而不检查。还有其他建议吗?
def location_check def locations_attributes=(values) self.location = Location.find_or_create_by_name(name: values) end end -
嗯,也许你应该把它改成
first_or_create:Location.where(name: values).first_or_create -
我想我仍然不确定您要做什么,但是 find_or_create_by_name 不接受哈希。它需要一个包含名称的字符串来查找或创建...
标签: ruby-on-rails ruby-on-rails-3 model