ruby-on-rails - 如何在部分内部呈现表单(Rails Simple_form)?
问题描述
以下是相关代码:
--- 应用程序/控制器/movies_controller.rb
def show
movie = convert_movie_data([Movie.find(params[:id])])
@movie = movie[0]
@movie_rating = movie[1]
@comments = Comment.all
if user_signed_in?
@new_comment = new_movie_comment
end
end
在控制台,@comments 返回
#<Comment id: nil, title: nil, comment: nil, user_id: 21, movie_id: 10, created_at: nil, updated_at: nil>
--- app/views/movies/show.html.haml
= render partial: 'shared/new', locales: { new_comment_form: @new_comment }
当用户未登录时,“= partial”处的部分呈现。
这就是问题所在(我怀疑):
--- app/views/shared/_new.html.erb
<% if user_signed_in? %>
<%= simple_form for new_comment_form:, method: :post, url: new_comment_path do |f| %>
<%= f.input :title %>
<%= f.input :comment %>
<%= f.button :submit %>
<% end %>
You are signed in
<% else %>
Please sign in to comment
<% end %>
我怀疑问题出在我为标签构建 simple_form 的方式上。
在控制器上,我注入了构建评论所需的值(current_user.id,movie_id),在显示视图中,我尝试通过语言环境(new_comment_form :) 传输实例变量,但我确定我做了一个简单形式的构造错误。
我意识到我没有提供错误消息这一事实。感谢您指出@z3r0ss
SyntaxError at /movies/21
syntax error, unexpected ','
...ple_form_for new_comment_form:, method: :post, url: new_comm...
... ^
/app/views/shared/_new.html.erb:12: syntax error, unexpected keyword_ensure, expecting end-of-input
ensure
^~~~~
我希望这会有所帮助,并再次感谢您的任何意见。
解决方案
首先,我会确保我正在发送Comment
from的新实例MoviesController
def show
@comment = Comment.new
end
对此有几点说明
1 - 请记住您@movie
使用 before_action 传递实例(如果您在其他控制器方法中使用该实例,这将很有用)
2 - 您可以使用 a 从视图访问属于电影的所有评论@movie.comments
(我假设那里有关联!)
关于表格,你可以试试这个:
<%= simple_form_for [@movie, @comment] do |f| %>
<%= f.input :title%>
<%= f.input :comment%>
<%= f.submit 'Post comment'%>
<% end %>
最后,在CommentsController
,记得重定向到你想要的任何地方。比如同款节目@movie
[...]
if @comment.save
redirect_to @movie
else
render 'movies/show'
end
推荐阅读
- javascript - 247freepoker.com 在什么程序中完成?
- firebase - 根据月份的日期在 Firebase 中保持文档字段的运行总数
- c# - 什么是 asp.net Web 表单中的“__VIEWSTATE_KEY”隐藏输入字段以及它的用途
- unity3d - unity 3d 反向浮点值
- mysql - 获取所有月份的列表和当月订购的产品数量,并且没有订单的月份应该有'0' - mysql
- python-3.x - Python/Pandas:如何检测趋势是否突然增加“X”量
- android - 哪个android api可以替代GMSGeometryIsLocationOnPathTolerance ios API?
- java - 为什么当通过 API 网关调用时,Java 中的这个 AWS Lambda 代码会返回“内部服务器错误”?
- javascript - 如何检查嵌套数组是否为空?
- android - 从 Firebase 问题中删除 android 应用