Skip to content

Instantly share code, notes, and snippets.

@werelax
Created September 21, 2011 19:30
Show Gist options
  • Save werelax/1233054 to your computer and use it in GitHub Desktop.
Save werelax/1233054 to your computer and use it in GitHub Desktop.
Serializing tag array in the model
# encoding: utf-8
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
ActiveRecord::Schema.define do
create_table :bookmarks do |t|
t.column :name, :string
t.column :tags, :text
end
end
class Bookmark < ActiveRecord::Base
# Así de sencillo!
serialize :tags, Array
end
# Ejemplos con las operaciones más comunes
p 'b1 = Un nuevo bookmark con tags: [tag1, tag2, tag3]'
b1 = Bookmark.create(:name => 'b1', :tags => ['tag1', 'tag2', 'tag3'])
y b1
p 'Añado un nuevo tag: "otra tag"'
b1.tags << 'otra tag'
y b1
p 'Incluye tag1?'
if b1.tags.include?('tag1') then p 'si' else p 'no' end
p 'Incluye tag9?'
if b1.tags.include?('tag9') then p 'si' else p 'no' end
p 'quitar tag "otra tag"'
b1.tags.delete 'otra tag'
y b1.tags
p 'Un par de bookmarks más...'
b2 = Bookmark.create(:name => 'b2', :tags => ['tag2', 'tag3', 'más tags'])
b3 = Bookmark.create(:name => 'b3', :tags => ['tag8', 'tag9'])
p 'Operaciones con los bookmarks de un usuario:'
user_bookmarks = Bookmark.all
p 'todas las tags del usuario:'
y all_user_tags = user_bookmarks.collect(&:tags).flatten.uniq
p 'los bookmarks con la tag "tag2:"'
y user_bookmarks.select {|b| b.tags.include?('tag2') }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment