[英]using two controllers in one view
我正在使用Rails在Ruby上的简单站点上创建联系表。 问题如下。 我有主控制器StaticPages
,使带有页眉和页脚的纯html。 现在,我制作了控制器Contacts
,它在单独的url上显示具有简单联系方式的视图。 当我尝试将此表格从StaticPages
添加到我的联系页面时,它不起作用。 我不知道如何告诉Rails这种形式应该不是从StaticPages
控制器而是从Contacts
控制器中找到方法。
这是我的代码:
接触控制器
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
@contact.request = request
if @contact.deliver
flash.now[:notice] = 'Thanks!'
else
flash.now[:error] = 'Error!'
render :new
end
end
end
StaticPages控制器
class StaticPagesController < ApplicationController
def home
end
def about_us
end
def contact_us
end
end
这是我需要在StaticPage contact_us上工作的表格
<div align="center">
<h3>Send us message</h3>
<%= simple_form_for @contact, :html => {:class => 'form-horizontal' } do |f| %>
<%= f.input :name, :required => true %>
<%= f.input :email, :required => true %>
<%= f.input :message, :as => :text, :required => true %>
<div class= "hidden">
<%= f.input :nickname, :hint => 'Leave this field blank!' %>
</div>
<div>
</br>
<%= f.button :submit, 'Send', :class=> "btn btn-primary" %>
</div>
<% end %>
</div>
我想我需要告诉Rails这种形式应该在寻找特定的控制器,但是我不知道如何。
请帮忙。
这不是您想要的,但是它应该可以按您想要的方式工作,您应该有一个contacts_helper.rb
,看起来应该像这样
module ContactsHelper
def contact_us
@contact = Contact.new
end
end
在你偏爱的地方
<%= simple_form_for contact_us, :html => {:class => 'form-horizontal' } do |f| %>
最后,您需要在application_controller.rb
包含您的帮助application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
...
include ContactsHelper
...
end
一种简单的选择是让StaticPages
contact_us
操作redirect_to new_contact_url
StaticPages
(假设表单位于app/views/contacts/new.html.erb
)
或者,您可以将表单放在app/views/shared/_new_contact.html.erb
,然后在contact_us
操作中放入@contact = Contact.new
,并让contact_us
模板render partial: "shared/new_contact", locals: { :contact => @contact }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.