Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use model callback methods? #918

Closed
hcyildirim opened this issue Sep 3, 2018 · 3 comments
Closed

How to use model callback methods? #918

hcyildirim opened this issue Sep 3, 2018 · 3 comments

Comments

@hcyildirim
Copy link

hcyildirim commented Sep 3, 2018

Hi,

I want to broadcast most used tags so I think I need something like after_save or after_create_commit how can I achieve this?

act-as-taggable model

self.tag_list.add(self.reason.scan(/#(\w+)/).flatten.uniq) unless self.reason.nil?

and my tag model inherits from act-as-taggable

class Tag < ActsAsTaggableOn::Tag
  after_save do
    puts "It should come here but it's not working"
  end
end

Thanks.

@stevendaniels
Copy link

Hi @ccoeder,

The issue you're facing is that the model you are using is adding tags to the ActsAsTaggableOn::Tag model, not the Tag model that you created. If you wanted to use callbacks you should try something like this:

class ActsAsTaggableOn::Tag
  after_save do
    puts "It should come here; it's working now"
  end
end

# generated with `rails g model User reason:string`
class User < ActiveRecord::Base
  acts_as_taggable
  def update_reason(reason)
    self.reason = reason
    self.tag_list.add(self.reason.scan(/#(\w+)/).flatten.uniq) unless self.reason.nil?

    reason
  end
end
# disable logging so that we can see the message
ActiveRecord::Base.logger = nil 

user = User.new
user.update_reason "#2"
user.save #=> "It should come here; it's working now"

In the future, questions like this are probably better addressed on sites like StackOverflow.

This issue can be closed.

@hcyildirim
Copy link
Author

Thank you!

@stoplion
Copy link

This is not working for me. Where should this file be located?
Model/ActsAsTaggableOn/Tag ?
or Model/Tag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants