I'm building a small app that let's you post recipes and micro posts. On the homepage a logged in user will see 2 forms one for posting a recipe one for posting a micro post. The problem: only one of the forms is working it seems the other post is handled by the wrong controller.
I found several related StackOverflow questions regarding this topic (one suggesting to use javascript, one with a solution based on :namespace in the form_for helper) but they didn't seem to work or are intended for other setups.
The views (.haml): Home
=provide(:title, 'Home')
- if signed_in?
.row
%aside.span4
%section
=render 'shared/user_info'
%section
=render 'shared/recipe_form'
%section
=render 'shared/micropost_form'
Partial 1: Recipe Form
%h3 Add recipe
= form_for(@recipe) do |f|
= render 'shared/error_messages', object: f.object
=f.label :name
=f.text_field :name
.field
=f.text_area :content, placeholder: 'Compose new recipe...'
=f.submit('Post recipe', class:'btn btn-large btn-primary')
Partial 2: Micropost Form
%h3 Add micropost
= form_for(@micropost) do |f|
= render 'shared/error_messages', object: f.object
.field
=f.text_area :content, placeholder: 'Compose new micropost...'
=f.submit('Post micropost', class:'btn btn-large btn-primary')
The error partial (.erb):
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Controller:
class MicropostsController < ApplicationController
before_action :signed_in_user
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = 'Micropost created!'
redirect_to root_url
else
render 'static_pages/home'
end
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
end
The controller for recipes is almost the same.
Routes excerpt:
resources :microposts, only: [:create, :destroy]
resources :recipes, only: [:create, :destroy]
Both forms work; but only when you fill them with correct values; Leaving a field blanc still gives an error; something seems to go wrong with the error partial...
When submitting a blanco recipe; see screen: here
Is there a way to get this working?
When a form has errors it indicates that the user has tried to fill it out. When you submit an empty recipe you don't need the micropost form and vice versa; a solution is to not render the other form on errors:
In the home view:
When you try to submit a form with errors you'll see the form you were submitting.
My guess is that you are rendering f.object twice, and instead you are rendering the last one. Change the loop variable name in one of the partials so the render partial don't catch it.
The render partials seems to be happening before the end tags.