On Apr 29, 7:13 pm, dusty <[email protected]> wrote:
> Have you tried the hook methods yet? You can specify a symbol and it
> will call that method, or you can specify a block and it will execute
> it.
Those are the hook class methods, which now require a plugin:
Sequel::Model.plugin :hook_class_methods
The recommended way going forward is to just use instance methods:
class Comment < Sequel::Model
many_to_one :post
def after_create
post.increment_comment_count
end
def after_destroy
post.decrement_comment_count
end
end
class Post < Sequel::Model
one_to_many :comments
def increment_comment_count
self.comment_count += 1
save
end
def decrement_comment_count
self.comment_count -= 1
save
end
end
Note that doing things in this way leads to race conditions. The
proper way to do this is to use a database trigger, but those are
obviously specific to each database. If you are using PostgreSQL,
look at my sequel_postgresql_triggers extension.
Also, you're migrations, while they work, probably should be changed:
class CreatePosts < Sequel::Migration
def up
create_table :posts do
primary_key :id
text :data
mediumint :comments_count
end
end
end
class CreateComments < Sequel::Migration
def up
create_table :comments do
primary_key :id
text :data
foreign_key :post_id, :posts
end
end
end
You should only use the uppercase names if you are using the generic
database types (e.g. a supported ruby class name such as Integer,
String, etc.). This is just a convention, but I think it's helpful to
differentiate between using the generic type support and the specific
type support.
Jeremy
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en
-~----------~----~----~----~------~----~------~--~---