我正在构建一个小应用程序,让您发布食谱和微帖。在主页上,登录用户将看到2个表单,用于发布用于发布微帖的食谱1。问题:只有一个表单正在工作,似乎另一个帖子由错误的控制器处理。
我发现了几个与此主题相关的StackOverflow问题(一个建议使用javascript,一个基于:form_for帮助程序中的命名空间的解决方案),但它们似乎无法正常工作或用于其他设置。< / p>
观点(.haml):主页
=provide(:title, 'Home')
- if signed_in?
.row
%aside.span4
%section
=render 'shared/user_info'
%section
=render 'shared/recipe_form'
%section
=render 'shared/micropost_form'
第1部分:食谱表格
%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')
第2部分:Micropost表格
%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')
错误部分(.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 %>
控制器:
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
食谱的控制器几乎相同。
路线摘录:
resources :microposts, only: [:create, :destroy]
resources :recipes, only: [:create, :destroy]
两种形式都有效;但只有当你用正确的值填充它们时;离开现场仍然会出错;错误部分似乎出现问题...
提交blanco食谱时;见屏幕:here
有没有办法让这个工作?
答案 0 :(得分:0)
我的猜测是你渲染f.object两次,而你正在渲染最后一个。更改其中一个部分中的循环变量名称,以便渲染部分不捕获它。
form_for(@recipes) do |fr|
form_for(@microposts) do |fm|
渲染部分似乎发生在结束标记之前。
答案 1 :(得分:0)
当表单出错时,表示用户已尝试填写表单。当您提交空配方时,您不需要微博形式,反之亦然;解决方案是不在错误上呈现其他形式:
在主页视图中:
- if signed_in?
.row
%aside.span4
%section
=render 'shared/user_info'
- if @micropost.nil? || @micropost.errors.empty?
%section
=render 'shared/recipe_form'
- if @recipe.nil? || @recipe.errors.empty?
%section
=render 'shared/micropost_form'
当您尝试提交有错误的表单时,您会看到您提交的表单。