首页 > 解决方案 > 如何在部分内部呈现表单(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
          ^~~~~

我希望这会有所帮助,并再次感谢您的任何意见。

标签: ruby-on-railssimple-form

解决方案


首先,我会确保我正在发送Commentfrom的新实例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

推荐阅读