Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ruby on rails - Calling a method from another controller

If I've got a method in a different controller to the one I'm writing in, and I want to call that method, is it possible, or should I consider moving that method to a helper?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could technically create an instance of the other controller and call methods on that, but it is tedious, error prone and highly not recommended.

If that function is common to both controllers, you should probably have it in ApplicationController or another superclass controller of your creation.

class ApplicationController < ActionController::Base
  def common_to_all_controllers
    # some code
  end
end

class SuperController < ApplicationController
  def common_to_some_controllers
    # some other code
  end
end

class MyController < SuperController
  # has access to common_to_all_controllers and common_to_some_controllers
end

class MyOtherController < ApplicationController
  # has access to common_to_all_controllers only
end

Yet another way to do it as jimworm suggested, is to use a module for the common functionality.

# lib/common_stuff.rb
module CommonStuff
  def common_thing
    # code
  end
end

# app/controllers/my_controller.rb
require 'common_stuff'
class MyController < ApplicationController
  include CommonStuff
  # has access to common_thing
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...