Created
December 5, 2016 16:32
-
-
Save sharshenov/df8b9556e4717d85da042af06abdb324 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
#возьмем, например, связь one-to-many и вложенными атрибутами | |
class Gallery < ActiveRecord::Base | |
has_many :images | |
accepts_nested_attributes_for :images | |
end | |
class Image < ActiveRecord::Base | |
belongs_to :gallery, required: true | |
end | |
# Допустим, мы создаем новую галерею сразу с картинками | |
Gallery.create name: 'Memes', images_attributes: [{file: 'pepe.jpg'}, {file: 'yoba.png'}] | |
# В момент валидации модели Image галерея еще не существует. Точнее, объект есть, а записи нет(gallery_id: nil). И активрекорд выдаст ошибку валидации. | |
# Когда мы используем inverse_of, мы, как бы, просим активрекорд довериться нам. Если мы передаем gallery: Gallery.new, то активрекорд уже не полезет в БД. | |
class Gallery < ActiveRecord::Base | |
has_many :images, inverse_of: :gallery | |
accepts_nested_attributes_for :images | |
end | |
class Image < ActiveRecord::Base | |
belongs_to :gallery, required: true, inverse_of: :images | |
end | |
# Здесь у каждого объекта Image уже есть "связь" с объектом Gallery, хотя все они еще не persisted | |
Gallery.create name: 'Memes', images_attributes: [{file: 'pepe.jpg'}, {file: 'yoba.png'}] | |
# Здесь при обновлении картинок валидация сущестования галереи уже не будет создавать по объекту галереи на каждую картинку, а будет использовать обекты из eager load'а (обратите внимание на includes) | |
Image.includes(:gallery).find_each {|image| image.update foo: "bar" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment