Home how to call action from model to controller in ruby on rails

# how to call action from model to controller in ruby on rails

raja
1#
raja Published in 2018-02-13 10:20:38Z
 I am trying to call 'checking' action from post model. class Post < ApplicationRecord after_commit :testing def testing @id = "#{self.id}" puts @id checking # call action to controller end end  posts_controller.rb def checking puts "not Working" end  I am trying to achieve the above, whereas it is not getting called.
Akash Srivastava
2#
Akash Srivastava Reply to 2018-02-13 10:31:38Z
 You should not be calling a controller action from a model. That's not how even controller methods are called. If you want to trigger an action, it should be either written as a target of a view form or input method, or as a redirect through another controller method itself. If you really want this action to be triggered (if you want the message after a record is saved to a listener url), I'd suggest using a lib such as HTTP::Net or a gem like HTTParty to trigger a call to the action, with its url or rails url_helper. That too, is not suggested, and/or is not the way to operate things in rails.
Manishh
3#
 You can do this by instantiating the controller. SomeController.new.some_action  However it is Not Recommended as your model logic should be independent of your controller logic. Your model should follow Single-responsibility Principle. A class should have only a single responsibility. You might need some common logic for controller and models or some service!!!!
 As it was said: the models should not know about controller. Depending on the reason, you can define checking in model and from Controller just call this method for current Post. if something should be set from Controller and checked in Model , you can use the approach defined here
 As many (or all) other said, you shouldn't call a Controller action from a Model. If you are saving/destroying and object from a Controller and you want to check is commit was called, you can do it in the controller, after saving or destroying. posts_controller.rb def create @post = current_user.posts.build(post_params) if @post.save checking end end def checking puts "Is is working" end  If this is not what you want, because you are specifically interested in the commit callback, you can change the code to this: posts_controller.rb def create @post = current_user.posts.build(post_params) @post.save if @post.commmited? checking end end def checking puts "Is is working" end  And add some logic to your Model: class Post < ApplicationRecord attr_accessor :commit_performed #unset the commit_performed attribute on first callbacks before_destroy :unset_commit before_validation :unset_commit #set the commit_performed attribute after commit after_commit :set_commit def unset_commit @commit_performed = false end def set_commit @commit_performed = true end def commited? @commit_performed end end