问题
I think the simplest way to explain this is with a contrived example. I am using Rails 2.3.8 with Ruby 1.8.7 and ActiveRecord to MySQL db.
I have the following (contrived) model in one engine (installed in vendor/plugins directory of main app):
# contrived_app/vendor/plugins/concerts_engine/app/models/
class Concert < ActiveRecord::Base
has_many :artists
belongs_to :venue
end
And the following (contrived) model in another engine:
# contrived_app/vendor/plugins/tickets_engine/app/models/
class Ticket < ActiveRecord::Base
belongs_to :concert
end
How can I include/extend
has_many :tickets
in the Concert model?
Also, is the load order important, and if so what happens if the Concert model hasn't been defined/loaded yet?
Is it possible to only include
belongs_to :concert
if Concert been defined?
回答1:
Turns out I can do the following in the tickets_engine:
# contrived_app/vendor/plugins/tickets_engine/config/initializers/concert_extensions.rb
# or
# contrived_app/config/initializers/concert_extensions.rb
Rails.logger.info "\n~~~ Loading extensions to the Concert model from #{__FILE__}\n"
Concert.class_eval do
has_many :tickets
end
Personally, my preferred method is to extend the concert model from the tickets_engine, but load order and dependencies are important. i.e. tickets_engine would need to add a dependency on the concerts_engine in it's gemspec, and concert_engine would need to be loaded before tickets_engine.
回答2:
I'm guessing you may need to require Ticket in your concert model. Or wrap the entire engine in a module and include that.
来源:https://stackoverflow.com/questions/5240948/how-to-extend-a-model-in-a-rails-engine-from-another-rails-engine