[Ruby] [Rails] How to run helper method used in main application with Administrate

1 minute read

Difficulty, what you want to do

\\Main application helper method cannot be used ///

This is when I used a gem called Administrate to create an admin screen in a Rails app**. When I tried to use the helper method defined in the helper file for use in the view of the main application in the view below admin, the following error occurred…

Screenshots 2020-07-21 21.00.03.png

image_present? is the helper method used in the view of the main app (what I define in helpers/shops_helper.rb)**. The main app doesn’t give a NoMethodError… what should I do? ? ?

Environment

  • Ruby 2.5.1
  • Rails 5.0.7.2
  • Administrate 0.14.0

Conclusion

1. Describe the following settings in the config/application.rb file. ** **2. Restart the application (server)

that’s all. It was easy lol

config/application.rb


module Hoge
  class Application <Rails::Application
# Other config may be written

# from here
    config.to_prepare do
      Administrate::ApplicationController.helper Hoge::Application.helpers
    end
# So far
  end
end

*Hoge is the application name. Normally, the application name when rails new is done should be described after the module on the first line.

Administrate::ApplicationController.helper Hoge::Application.helpers

Please replace the Hoge part of with your own app name.

It was firmly listed in Issues on GitHub and it was resolved

Best way to include main app helper modules in administrate? #334 Screenshot 2020-07-21 20.51.34.png

Digression

If you look at Issues on GitHub mentioned in the reference article, there seems to be another method.

Screenshot 2020-07-21 20.52.13.png

This method is

  1. Create an administrate directory under the helpers directory
  2. Create the application_helper.rb file there
  3. Redefine the helper method there It seems that way.

I tried it

helpers/administrate/application_helper.rb


module Administrate::ApplicationHelper
  def image_present?(shop)
    if shop.shop_images.present?
      image_tag "#{shop.shop_images[0].shop_image}", class:'top-cover-img shop-img'
    else
      image_tag asset_path('no-image.png'), class:'top-cover-img shop-img'
    end
  end
end

The point is, when declaring module, class inheritance? It seems that it is to describe (Administrate::ApplicationHelper). Without this, a Routing Error will occur. Screenshots 2020-07-21 21.10.13.png

Can be achieved, but violates the DRY principle

Although it could be realized by the above method for the time being, since it means that the same helper method is defined twice, I thought that it violates the DRY principle.

We recommend you to use the method at the beginning because you don’t have to create unnecessary files.