Last active
August 29, 2015 14:07
-
-
Save nathanjsharpe/bf16da924bc0718b02d7 to your computer and use it in GitHub Desktop.
i18n + associations?
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 Image < ActiveRecord::Base | |
belongs_to :snippet | |
end |
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 Snippet < ActiveRecord::Base | |
has_many :images, -> { where(id: image_ids) } | |
translates :image_ids | |
serialize :image_ids, Array | |
before_save :update_image_ids | |
def update_image_ids | |
image_ids = images.select(:id).map(&:id) | |
end | |
def remove_images_for_locale(image_ids_to_remove) | |
image_ids = image_ids - Array.new(image_ids_to_remove) | |
return image_ids if save | |
false | |
end | |
def add_images_for_locale(image_ids_to_add) | |
image_ids = (image_ids + Array.new(image_ids_to_add)).uniq | |
return image_ids if save | |
false | |
end | |
end | |
# I18n.locale = 'en-US' | |
# @snippet = Snippet.new | |
# @snippet.images << Image.where(id: [1,2,3]) | |
# @snippet.add_images_for_locale([1,2,3]) | |
# @snippet.images => Images 1,2,3 | |
# I18n.locale = 'en-UK' | |
# @snippet.remove_images_for_locale([1,2]) | |
# @snippet.images => Image 3 | |
# I18n.locale = 'en-US' | |
# @snippet.images => Images 1,2,3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment