DanielsV
DanielsV

Reputation: 892

using two controllers in one view

I'm making contact form on simple site using ruby on rails. Problem is following. I have main controller StaticPages that makes plain html with header and footer. Now i made controller Contacts that displays view with simple contact form on separate url. When i try to add this form to my contact page from StaticPages it doesn't work. i don't know how to tell rails that this form should find method not from StaticPages controller but from Contacts controller.

Here is my code:

Contacts controller

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 controller

class StaticPagesController < ApplicationController

  def home
  end

  def about_us
  end

  def contact_us
  end

end

and here is the form i need to work on 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>

I guess I need to tell rails that this form should be looking for particular controller, but I don't know how.

Please help.

Upvotes: 0

Views: 711

Answers (2)

Clark
Clark

Reputation: 616

This isn't quite what you're looking for but it should work the way you want, you should have a contacts_helper.rb, that should look like this

module ContactsHelper
  def contact_us
    @contact = Contact.new
  end
end

In your partial you'll want

<%= simple_form_for contact_us, :html => {:class => 'form-horizontal' } do |f| %>

And finally you need to include your helper, in 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

Upvotes: 1

Rob Mulholand
Rob Mulholand

Reputation: 899

One easy option would be to have the StaticPages contact_us action redirect_to new_contact_url (assuming that form lives at app/views/contacts/new.html.erb)

Alternatively, you could put the form in app/views/shared/_new_contact.html.erb, then put in @contact = Contact.new in your contact_us action, and have the contact_us template render partial: "shared/new_contact", locals: { :contact => @contact }.

Upvotes: 0

Related Questions