【问题标题】:using two controllers in one view在一个视图中使用两个控制器
【发布时间】:2015-04-26 22:30:42
【问题描述】:

我正在使用 ruby​​ on rails 在简单的网站上制作联系表格。问题如下。我有主控制器StaticPages,它可以制作带有页眉和页脚的纯html。现在我制作了控制器Contacts,它在单独的网址上显示带有简单联系表单的视图。当我尝试将此表单从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

静态页面控制器

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 这个表单应该寻找特定的控制器,但我不知道如何。

请帮忙。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller


【解决方案1】:

这不是你要找的东西,但它应该按照你想要的方式工作,你应该有一个 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中包含你的助手

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

【讨论】:

    【解决方案2】:

    一个简单的选择是使用StaticPages contact_us 操作redirect_to new_contact_url(假设表单位于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 =&gt; @contact }

    【讨论】:

    • 但是我不会从contact_us 页面丢失我所有的html 正文并以原始形式结束吗?我需要在我的所有contact_us 中都有工作表格,这样页面就会显示所有内容。
    • 编辑了我的答案以提供另一种可能解决您的问题的方法
    • 刚刚编辑的代码。它仍然抛出这个错误First argument in form cannot contain nil or be empty你怎么看?
    • contact_usStaticPagesController 的操作有 @contact = Contact.new 吗?这似乎可以保证 @contact 不是零 ...
    • 是的,我写的。仍然是同样的问题。这没有任何意义吧?如果我使用带有单独 url 的旧配置(例如 /contacts 但现在使用 /contact_us
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多