Simple_form: 参数未通过

Simple_form: Parameter not passing

我正在尝试为网站实现评论功能。到目前为止,我可以将我想要评论的电影的 movie_id 传递到我创建评论的页面(这是默认的脚手架视图)。之后,我尝试将 movie_id 传递给 comments_controllercreate 方法,但它不会通过。我尝试将其 class (params[:movie_id].class) 分配给 comment 属性,它显示 NilClass.

我的代码:

comments_controller.rb

def create
    @comment = Comment.new
    @comment.comment = params[:comment].values.first
    @comment.user_id = current_user.id
    @comment.movie_id = params[:movie_id]
    #...
end

_form.html.erbnew 页面呈现的那个)

<%= simple_form_for(@comment) do |f| %>
    <%= f.error_notification %>

    <div class="form-inputs">
      <%= f.input :comment, label: false, placeholder: 'Your opinion'%>
      <%= f.hidden_field :movie_id, input_html: { value: params[:movie_id] } %>
    </div>

    <div class="form-actions">
      <%= f.button :submit %>
    </div>
<% end %>

html 文件中的 params[:movie_id] 实际上是我想要的,我尝试将其添加为占位符并且它具有正确的值。

这可能是一个愚蠢的错误,但是,我真的被卡住了...

感谢您的宝贵时间。

<%= f.hidden_field :movie_id, params[:movie_id] %>

这应该有用吗?

我还是会这样做,因为在控制器中你可能有 @comment = Comment.new 在控制器中使用 form_for,@comment.movie_id = params[:movie_id] 然后在表单中使用 @comment.movie_id , 只是为了让它更干净?

您的 html 有误。隐藏字段应该为隐藏字段使用正确的 rails 语法,或者使用简单的格式语法。

Rails 语法:

 <%= f.hidden_field :movie_id, value: params[:movie_id] %>

简单的格式语法:

 <%= f.input :movie_id, as: :hidden, input_html: { value: params[:movie_id] } %>

在控制器中:

@comment.movie_id = params[:comment][:movie_id]

顺便说一句,使用强参数的良好形式如下

@comment.movie_id = comment_params[:movie_id]
private
def comment_params
  params.require(:comment).permit(:movie_id, ...(and others..)
end