Reputation: 25
I need to create a controller
instance from another controller
for using its methods. When I creating
c = SomeController.new
c.some_method
some_method use params[]
, and then I have an error NoMethodError: undefined method 'parameters' for nil:NilClass
.
How can I pass params to the controller
?
Upvotes: 2
Views: 863
Reputation: 102248
You don't instantiate controllers in Rails - its done by the router when it matches a request to a route.
Its just not done because it violates the way MVC in Rails works - one request = one controller. You also need to pass the entire env hash from rack into the controller for it even work properly.
But really - don't. There are much better ways.
If you need to share a method between controllers there are better ways such as using inheritance:
class ApplicationController
def some_method
end
end
class FooController < ApplicationController
end
class BarController < ApplicationController
end
Or mixins:
# app/controllers/concerns/foo.rb
module Foo
def some_method
end
end
class BarController < ApplicationController
include Foo
end
class BazController < ApplicationController
include Foo
end
If you instead need to move a request from one controller action to another you should be redirecting the user.
Upvotes: 0
Reputation: 1035
The thing you are trying to do it not recommended any framework. You probable have some code that you wanted in multiple controllers. To achieve your desired behavior, extract the common code to library can call that in any controller you want.
Upvotes: 2