我刚创建了第一个引擎。它增加了几条新的路线,如:
Rails.application.routes.draw do
scope :module => 'contact' do
get "contact", :to => 'contacts#new'
get "contact/send_email", :to => 'contacts#send_email', :as => 'send_email'
end
end
然后,在/websites/Engines/contact/app/controllers/contacts_controller.rb中,我有:
module Contact
class ContactsController < ApplicationController
# Unloadable marks your class for reloading between requests
unloadable
def new
@contact_form = Contact::Form.new
end
def send_email
@contact_form = Contact::Form.new(params[:contact_form])
if @contact_form.valid?
Notifications.contact(@contact_form).deliver
redirect_to :back, :notice => 'Thank you! Your email has been sent.'
else
render :new
end
end
end
end
我将它加载到客户端应用程序的控制台中以向我自己证明一些基础工作正在运行并很快出现此加载错误(我通过在浏览器中重现问题来确认):
ruby-1.8.7-p302 > Contact::Form.new
=> #<Contact::Form:0x2195b70>
ruby-1.8.7-p302 > app.contact_path
=> "/contact"
ruby-1.8.7-p302 > r = Rails.application.routes; r.recognize_path(app.contact_path)
LoadError: Expected /websites/Engines/contact/app/controllers/contacts_controller.rb to define ContactsController
你有它; / contact访问引擎的contacts_controller.rb,但控制器在模块Contact内的事实使得它无法识别。
我做错了什么?
答案 0 :(得分:4)
您的app/controllers/contacts_controller.rb
实际上是定义了Contact::ContactsController
,而不是Rails期望的ContactsController
。
问题在于您的路线,它们应该像这样定义:
Rails.application.routes.draw do
scope :module => 'contact' do
get "contact", :to => 'contact/contacts#new'
get "contact/send_email", :to => 'contact/contacts#send_email', :as => 'send_email'
end
end
答案 1 :(得分:0)
感谢@ ryan-bigg和@nathanvda他们的答案为我解决了这个问题。简而言之,我最终使用了以下路线:
Rails.application.routes.draw do
scope :module => 'contact' do
get "contact", :to => 'contacts#new'
post "contact/send_email", :to => 'contacts#send_email', :as => 'send_email'
end
end
使用以下控制器:
module Contact
class ContactsController < ApplicationController
def new
@contact_form = Contact::Form.new
end
def send_email
@contact_form = Contact::Form.new(params[:contact_form])
if @contact_form.valid?
Contact::Mailer.contact_us(@contact_form).deliver
redirect_to :back, :notice => 'Thank you! Your email has been sent.'
else
render :new
end
end
end
end
但似乎是最后一篇文章是@ nathanvda关于移动contacts_controller的建议:
/app/controllers/contacts_controller.rb
到
/app/controllers/contact/contacts_controller.rb
谢谢你们的帮助!