Posted By


filiptepper on 10/07/08

Tagged


Statistics


Viewed 485 times
Favorited by 1 user(s)

has_many validates_presence_of


/ Published in: Rails
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # migrations
  2.  
  3. class CreateClients < ActiveRecord::Migration
  4. def self.up
  5. create_table :clients do |t|
  6. t.string :name, :length => 255, :null => false
  7. t.timestamps
  8. end
  9. end
  10. end
  11.  
  12. class CreateEmails < ActiveRecord::Migration
  13. def self.up
  14. create_table :emails do |t|
  15. t.integer :client_id
  16. t.string :email, :length => 64, :null => false
  17. t.timestamps
  18. end
  19. end
  20. end
  21.  
  22. # model
  23.  
  24. class Email < ActiveRecord::Base
  25. belongs_to :client
  26. validates_presence_of :email
  27. validates_presence_of :client_id
  28. end
  29.  
  30. class Client < ActiveRecord::Base
  31. has_many :emails
  32. end
  33.  
  34. # ./script/console
  35. >> c = Client.new('name' => 'Client')
  36. >> e = Email.new('email' => '[email protected]')
  37. >> c.emails << e
  38. >> c.save!
  39. # ActiveRecord::RecordInvalid: Validation failed: Emails is invalid
  40. >> e.errors.full_messages
  41. => ["Client can't be blank"]
  42.  
  43. # ./script/console
  44. >> c = Client.new('name' => 'Client')
  45. >> e = Email.new('email' => '[email protected]')
  46. >> e.client = c
  47. >> c.save!
  48. => true

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.