Skip to content

Instantly share code, notes, and snippets.

@mytrile
Created December 5, 2008 13:27
Show Gist options
  • Select an option

  • Save mytrile/32330 to your computer and use it in GitHub Desktop.

Select an option

Save mytrile/32330 to your computer and use it in GitHub Desktop.
class Category
include DataMapper::Resource
property :id, Serial
property :name, String
property :description, Text
property :url, String
property :created_at, DateTime
property :updated_at, DateTime
has n, :images
has n, :users, :through => Resource
end
# using merb console
>> user = User.get(1)
~ SELECT `id`, `login`, `email`, `image`, `created_at`, `updated_at`, `crypted_password`, `salt` FROM `users` WHERE (`id` = 1) ORDER BY `id` LIMIT 1
=> #<User id=1 login="mitkok" email=nil description=<not loaded> image=nil created_at=#<DateTime: 13255947691/5400,1/12,2299161> updated_at=#<DateTime: 13255947691/5400,1/12,2299161> crypted_password="132dd5baa9b6f8a6b2e85b3fd439aac99263f85d" salt="11a0b1b5cd533613d8b961d18ad5276ca865d8d9">
>> user.categories
~ SELECT `categories`.`id`, `categories`.`name`, `categories`.`url`, `categories`.`created_at`, `categories`.`updated_at` FROM `categories` INNER JOIN `categories_users` ON (`categories`.`id` = `categories_users`.`category_id`) WHERE (`categories_users`.`user_id` = 1) GROUP BY `categories`.`id`, `categories`.`name`, `categories`.`url`, `categories`.`created_at`, `categories`.`updated_at` ORDER BY `categories`.`id`
=> []
>> cat = Category.new
=> #<Category id=nil name=nil description=nil url=nil created_at=nil updated_at=nil>
>> cat.name = 'Homeless dogs'
=> "Homeless dogs"
>> cat.description = 'Really dirty and dangerous!'
=> "Really dirty and dangerous!"
>> user.categories << cat
~ INSERT INTO `categories` (`name`, `updated_at`, `description`, `created_at`) VALUES ('Homeless dogs', '2008-12-05 15:26:08', 'Really dirty and dangerous!', '2008-12-05 15:26:08')
~ SELECT `category_id`, `user_id` FROM `categories_users` WHERE (`user_id` IN (1)) ORDER BY `category_id`, `user_id`
=> [#<Category id=3 name="Homeless dogs" description="Really dirty and dangerous!" url=nil created_at=#<DateTime: 13255952723/5400,1/12,2299161> updated_at=#<DateTime: 13255952723/5400,1/12,2299161>>]
# Here category is created, but the association in table categories_users not.
class User
include DataMapper::Resource
# Attributes
property :id, Serial
property :login, String
property :email, String
property :description, Text
property :image, String
property :created_at, DateTime
property :updated_at, DateTime
# Associations
has n, :categories, :through => Resource
# Validations
validates_present :login, :password, :password_confirmation
validates_is_unique :login
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment