Home > Mobile >  Rails best practice for calling a model method from a different controller
Rails best practice for calling a model method from a different controller

Time:07-13

I have Model_a, model_a_controller and Model_b. I have a method in model_b that I would like to call in model_a_controller. But I am not sure what the best practice for doing so would be. This is my method right now:

def method
   id = Model_b.method
   .... some other stuff
end 

Im calling the method directly from the model but is it better rails practice to perhaps make an instance of the model and then call the method from that instance? Something like

    def method
   @model_b = Model_b
   id = @model_b.method
   .... some other stuff
end 

Im not quite sure what the best practice would be or if my alternative would make sense; Any pointers are welcome.

CodePudding user response:

It depends what you'd like to achieve and what's the context. I can only answer with some quick guiding questions that might be a start point for your own decision making.

I see two different threads in you question:

  1. Class method vs instance method For this it doesn't matter where you call the method_b. It's about its logic and responsibility. What does this method suppose to do? Do you need a Model B instance (e.g. @instance_B.valid?)? Or is it a behaviour related to class only or all Model B instances (e.g. Model_B.count)? Think about the outcome of this method and what you need to achieve it.

  2. Where to call the method_b As a rule of thumb, a good practice in rails is to keep skinny controller. Is there any relationship between model A and model B? Then probably it's better to call the method_b in the model A. Maybe you should consider adding the service layer for that? https://www.toptal.com/ruby-on-rails/rails-service-objects-tutorial Consider relationships between models and the controller actions.

There are no strict rules that always work. It depends on the business context, the app design and direction of the development. If you provide more specific example, then we can give more specific advice and discuss pros & cons of different approaches.

CodePudding user response:

Maybe you can create a service object like this: In app, create a folder services(app/services)

Inside services folder you can organize all the services for your project.

services/model_b_service/model_b_method.rb

module ModelBService
class ModelBMethod
 def initialize
 end
 def call
 .. logic goes here
 end
end

So, in your controller:

def method
   id = ModelBService::ModelBMethod.new.call
   .... some other stuff
end 

If you want to pass arguments just ModelBService::ModelBMethod.new(args).call and fetch in initialize method

  • Related