0

我刚刚创建了我的第一个引擎。它添加了几条新路线,如下所示:

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 内的事实使其无法识别。

我究竟做错了什么?

4

2 回答 2

4

app/controllers/contacts_controller.rb实际上是在定义Contact::ContactsController,而不是ContactsControllerRails 期望的。

问题出在您的路线上,它们应该这样定义:

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
于 2011-03-26T22:19:26.123 回答
0

Thanks to @ryan-bigg and @nathanvda their answers in conjunction fixed this issue for me. In short, I ended up using the following routes:

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

with the following controller:

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

but what seemed to be the final piece was @nathanvda's suggestions to move the contacts_controller from:

/app/controllers/contacts_controller.rb

to

/app/controllers/contact/contacts_controller.rb

Thank you both for your help!

于 2011-04-07T19:08:20.157 回答