简体   繁体   中英

Rails: hook_for :orm not finding active_record

I'm writing a custom generator. For the most part, the generator is able to use hooks successfully. For instance,

hook_for :resource_route, in: :rails, required: true

Invokes resource_route as expected. However:

hook_for :orm, in: :rails, required: true

Returns the error:

error  active_record [not found]

I'm assuming this is because the active_record_generator is located in a dramatically different directory from other generators, such as the resource_route generator.

rails / activerecord / lib / rails / generators / active_record.rb

rails / railties / lib / rails / generators / rails / resource_route / resource_route_generator.rb

Is there a way to get my generator to properly hook active record?

I eventually hacked this, only after I managed a dodgy work around using hook_for and remove_hook_for fiasco. My advise leave it alone it's not worth the trouble.

This way uses much less code for way more result for your effort.

There are a few tricks you may want to use.

  1. Stay within the Rails::Generators namespace.

    The folder structure I used was:

     lib/generators/my_own_model/ templates/ my_own_model_generator.rb
  2. Set the config in the model for the generator you want to create

    That's all you need to overcome the error whatever [not found] headaches.

    Code looks like this

    require 'rails/generators/active_record/model/model_generator' module Rails module Generators hide_namespace 'my_own_model' class Railtie < ::Rails::Engine if config.respond_to?(:app_generators) config.app_generators.orm = :my_own_model else config.generators.orm = :my_own_model end end class MyOwnModelGenerator < ActiveRecord::Generators::ModelGenerator source_root "#{base_root}/active_record/model/templates" # all public methods will get executed by rails g protected # these won't but can be overwritten by sub classes private # these are still exposed to your templates nifty end end end
  3. The third trick is to hide your generator name. Why is that you ask? Well you may like to know that you won't be needing it anymore.

     $ rails g model MyNewModel generator:belongs_to my_own:boolean

You have just created a default generator which you can overwrite again from your template folders. =)

nJoy!

至少在 Rails 5 中,你需要指定生成器的类型 (:model, :migration, :application_record)

hook_for :orm, as: :model

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM