Last active
August 29, 2015 14:03
-
-
Save waaadim/133c4fc94c359a823e42 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Country < ActiveRecord::Base | |
validates :name, uniqueness: true | |
validates :name, presence: true | |
has_many :regions, dependent: :destroy#, inverse_of: :country | |
validates_associated :regions | |
accepts_nested_attributes_for :regions | |
end | |
class Region < ActiveRecord::Base | |
validates :name, presence: true | |
validates_uniqueness_of :name, scope: :country_id | |
belongs_to :country | |
end | |
# rails console -> | |
# simple | |
1. Country.create(name: 'name') | |
2. Country.first.regions.create(name: 'name') # creates the region | |
3. Country.first.regions.create(name: 'name') # doesn't create the region (which is what I'd expect) | |
# with mass assignment | |
1. c2 = Country.create(name: 'name2') | |
2. c2.attributes = { regions_attributes: [ { name: 'nn' }, { name: 'nn' } ]} | |
3. c2.save # creates duplicates. why?? | |
# -------------------------------------------- | |
# test2 | |
c1 = Country.create(name: 'name11') | |
c1.regions.create(name: 'dd') | |
r = c1.regions.create(name: 'dd') | |
pp r.errors | |
pp c1.regions | |
pp '------------------------' | |
data = { | |
regions_attributes: [ { name: 'dd' }, { name: 'dd' } ] | |
} | |
c2 = Country.create(name: 'name2') | |
c2.attributes = data | |
c2.save # creates duplicates. why?? | |
pp c2.errors | |
pp c2.regions | |
# test output | |
#<ActiveModel::Errors:0x00000006c7bf40 | |
@base= | |
#<Region id: nil, name: "dd", country_id: 47, created_at: nil, updated_at: nil>, | |
@messages={:name=>["has already been taken"]}> | |
[#<Region id: 52, name: "dd", country_id: 47, created_at: "2014-07-01 10:54:53", updated_at: "2014-07-01 10:54:53">, | |
#<Region id: nil, name: "dd", country_id: 47, created_at: nil, updated_at: nil>] | |
"------------------------" | |
#<ActiveModel::Errors:0x00000006eb97a8 | |
@base= | |
#<Country id: 48, name: "name2", created_at: "2014-07-01 10:54:53", updated_at: "2014-07-01 10:54:53">, | |
@messages={}> | |
[#<Region id: 53, name: "dd", country_id: 48, created_at: "2014-07-01 10:54:53", updated_at: "2014-07-01 10:54:53">, | |
#<Region id: 54, name: "dd", country_id: 48, created_at: "2014-07-01 10:54:53", updated_at: "2014-07-01 10:54:53">] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment