Reputation: 236
I am new to rails and still working on fundamentals, so any tips and advice are greatly appreciated!
I've made a functional contact page on a website, and I would like to be able to render the form and functionality of inside a tab on a different page. I have the following code in the static_pages folder in my views folder:
<div id="tabs">
<ul>
<li><a href="#tabs-1">About</a></li>
<li><a href="#tabs-5">Contact</a></li>
</ul>
<div id="tabs-1">
<%= render "shared/about"%>
</div>
<div id="tabs-5">
<%= render "contact/new"%>
</div>
where <%= render "contact/new"%> corresponds to the new.html.erb file in contact in views.
the relevant code inside my routes.rb is
match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :as => 'contact', :via => :post
and here is my controller:
class ContactController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
NotificationsMailer.contact_pr(@message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
However, It seems that whatever I try I still am unable to render the form. I apologize if this is a very simple question, and I am mostly interested in getting better at fundamentals in Ruby on Rails so any advice is appreciated! Thanks!
Upvotes: 0
Views: 112
Reputation: 51151
If you want to render this form in other templates (and you do), you should extract it to partial named for example: _form.html.erb
.
Then, you should put
<%= render 'contact/form' %>
everywhere you need this partial in view (including new.html.erb
template).
When you are done with this, you should leave
render :new
in controller, as it works a little bit different than in view and it renders appropriate action template instead of partial.
Of course, you need to set @message
variable everywhere you need this partial. Or, you can put in your partial:
<%= form_for(@message || Message.new) do |f| %>
More info about layouts and rendering here.
Upvotes: 1