【问题标题】:Rails 3: Find_or_create_by_name not savingRails 3:Find_or_create_by_name 不保存
【发布时间】: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_createLocation.where(name: values).first_or_create
  • 我想我仍然不确定您要做什么,但是 find_or_create_by_name 不接受哈希。它需要一个包含名称的字符串来查找或创建...

标签: ruby-on-rails ruby-on-rails-3 model


【解决方案1】:

基于 cmets,我会这样重构它:

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')

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

【讨论】:

  • 嗨@Philip!感谢您的回答!这在我的“位置”控制器中效果很好,但是,我在“位置”模型中进行测试,因为我需要通过嵌套表单将它应用到我的“帖子”中。我认为该模型将是做到这一点的最佳方式。我不确定在通过@post = current_blogger.blog_posts.new(params[:post]) 之类的变量传递变量时如何应用“find_or_create”我感谢到目前为止的所有帮助,还有其他关于这最后一点的想法吗?
  • 我不知道...您需要深入研究nested_attributes 以查看可用的内容。
【解决方案2】:

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

【讨论】:

  • 嗨@lifejuggler,是的,这不是因为错字(尝试了几个不同的名字)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多