【发布时间】:2014-06-18 16:50:18
【问题描述】:
我正在构建一个小应用程序,让您可以发布食谱和微博。在主页上,登录用户将看到 2 个表单,一个用于发布食谱,一个用于发布微博。问题:只有一个表单在工作,似乎另一个帖子是由错误的控制器处理的。
我发现了几个与此主题相关的 StackOverflow 问题(一个建议使用 javascript,一个使用基于 form_for 帮助程序中的 :namespace 的解决方案),但它们似乎不起作用或适用于其他设置。
视图 (.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')
第二部分:微博表单
%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]
两种形式都有效;但只有当你用正确的值填充它们时;保留字段 blanc 仍然会出错;错误部分似乎出了点问题......
当提交一个 blanco 食谱时;查看屏幕:here
有没有办法让它工作?
【问题讨论】:
-
问题是您的haml标签没有正确关闭,并且食谱表单正在扩展自己,直到微博按钮结束标签。您必须正确关闭它们
-
更改 |f|如果你能找到错误,第二部分可能就足够了。
-
haml 看起来不错,食谱表格在部分标记之前停止。
标签: ruby-on-rails ruby forms