I've got a code that almost repeats itself in three of my controllers and i was wondering: is there a way to render partials inside controllers? I'll clarify, i want to write the same piece of ruby code and render it in each one of the controllers. Anyone know a way to do that? thanks
I'm very confused by your question; I don't see what it has to do with partials. However, if I understand correctly, what you have is something like.
class FooController < ApplicationController
def my_method
end
end
class BarController < ApplicationController
def my_method
end
end
class BazController < ApplicationController
def my_method
end
end
And you want to DRY it up by abstracting the my_method
method to a single place. The solution is to define it on ApplicationController
, which the other three controllers all inherit from.
There are two solutions, the module, and playing with the inheritance
Define a module with your custom code and include it in your controllers
module MyCustomModule
def method_1
#code ...
end
def method_2
#code ...
end
def method_2
#code ...
end
end
Then in your controllers :
class MyController < AplicationController
include MyCustomModule
end
If you don't mind having all your controllers ending up with these methods, simply define them in the application controller
class ApplicationController < ActionController::Base
# ...
def method_1
#code
end
# And so on ...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.