如何在部分内部渲染表单(Rails Simple_form)?

以下是相关代码:

--- app / controllers / 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 }

用户未登录时,呈现“ =部分”处的部分。

问题出在这里(我怀疑):

--- 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:,url: new_comm...
...                              ^
/app/views/shared/_new.html.erb:12: syntax error,unexpected keyword_ensure,expecting end-of-input
          ensure
          ^~~~~

我希望这会有所帮助,再次感谢您的任何投入。

adlofboy 回答:如何在部分内部渲染表单(Rails Simple_form)?

首先,我要确保要从Comment发送一个新的MoviesController实例

def show
  @comment = Comment.new
end

一些注意事项

1-请记住,您通过一个{_1}}实例传递了before_action(如果在其他控制器方法中使用该实例,这将很有用)

2-您可以使用@movie从视图中访问属于电影的所有评论(我假设那里存在关联!)

关于表格,您可以尝试以下操作:

@movie.comments

最后,记得在<%= simple_form_for [@movie,@comment] do |f| %> <%= f.input :title%> <%= f.input :comment%> <%= f.submit 'Post comment'%> <% end %> 处重定向到您想要的任何位置。例如,显示相同的CommentsController

@movie
,

也许您可以更清楚地了解自己的错误。从外观上看,这似乎是语法错误。应该是simple_form_for new_comment_form,而不是simple_form for new_comment_form:

本文链接:https://www.f2er.com/3070761.html

大家都在问