validates_associated似乎不起作用

时间:2014-08-06 22:12:43

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

我想问你一个关于帮助者validates_associated的问题,因为我需要验证一个asocciacion。当我尝试保存一本没有关联的新书时,这个一个库验证不起作用

这是我的schema.rb

ActiveRecord :: Schema.define(版本:20140806165743)做

  create_table "books", force: true do |t|
    t.string   "title"
    t.integer  "price"
    t.integer  "library_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "libraries", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end     
end

这些是我的两个模型

class Library < ActiveRecord::Base
 has_many :books 
 validates_associated :books
end

class Book < ActiveRecord::Base
 belongs_to :library
end

Rails控制台

library=Library.new(name: "Rayuela")
 => #<Library id: nil, name: "Rayuela", created_at: nil, updated_at: nil> 
2.0.0-p481 :003 > library.save
   (0.2ms)  SAVEPOINT active_record_1
  SQL (3.6ms)  INSERT INTO "libraries" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Wed, 06 Aug 2014 21:50:56 UTC +00:00], ["name", "Rayuela"], ["updated_at", Wed, 06 Aug 2014 21:50:56 UTC +00:00]]
   (0.1ms)  RELEASE SAVEPOINT active_record_1
 => true 
2.0.0-p481 :004 > book1=Book.new(title:"Ali Baba",price:50)
 => #<Book id: nil, title: "Ali Baba", price: 50, library_id: nil, created_at: nil, updated_at: nil> 
2.0.0-p481 :005 > book1.save
   (0.2ms)  SAVEPOINT active_record_1
  SQL (0.8ms)  INSERT INTO "books" ("created_at", "price", "title", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Wed, 06 Aug 2014 21:51:46 UTC +00:00], ["price", 50], ["title", "Ali Baba"], ["updated_at", Wed, 06 Aug 2014 21:51:46 UTC +00:00]]
   (0.1ms)  RELEASE SAVEPOINT active_record_1
 => true 

book1保存在数据库中,无需与库关联 它有library_id = nil ??????????????

3 个答案:

答案 0 :(得分:2)

validates_associated只是运行validations中指定的associated object's class,它对foreign keys没有任何作用。

因此,validates_associated :books模型中的Library只会运行validations模型中指定的Book,如果有) 。您的validation模型中未指定Book,因此validates_associated :books失败。

您需要在validates :library_id, :presence=>true模型中使用Book作为您的目的。

class Book < ActiveRecord::Base
 belongs_to :library 
 validates :library_id, :presence=>true
end

答案 1 :(得分:0)

您还可以将validates_presence_of用于关联数据。它验证指定的属性是否为空(由Object#blank定义?)。默认情况下会在保存时发生。

class Library < ActiveRecord::Base
 has_many :books 
 validates_presence_of :library_id
end

library_id必须位于对象中且不能为空。的 More Details

答案 2 :(得分:0)

也许你可以在你的书模型中尝试这个,而不是库:

class Book < ActiveRecord::Base
  belongs_to :library
  validates_presence_of :library
end