Multiple Forms on one Ruby page using Rails 4 -
i'm building little app let's post recipes , micro posts. on homepage logged in user see 2 forms 1 posting recipe 1 posting micro post. problem: 1 of forms working seems other post handled wrong controller.
i found several related stackoverflow questions regarding topic (one suggesting utilize javascript, 1 solution based on :namespace in form_for helper) didn't seem work or intended 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 together recipe = form_for(@recipe) |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 together micropost = form_for(@micropost) |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"> form contains <%= pluralize(object.errors.count, "error") %>. </div> <ul> <% object.errors.full_messages.each |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 recipes same.
routes excerpt:
resources :microposts, only: [:create, :destroy] resources :recipes, only: [:create, :destroy]
both forms work; when fill them right values; leaving field blanc still gives error; seems go wrong error partial...
when submitting blanco recipe; see screen: here
is there way working?
my guess rendering f.object twice, , instead rendering lastly one. alter loop variable name in 1 of partials render partial don't grab it.
form_for(@recipes) |fr| form_for(@microposts) |fm|
the render partials seems happening before end tags.
ruby-on-rails ruby forms
No comments:
Post a Comment