Rails 上 Ruby 未保存嵌套评论正文

Nested Comment body not being saved Ruby on Rails

我正在用头敲桌子试图弄清楚为什么评论会发 comment.body,但是当我进入 IRB body=nil 时,它不会显示在 App 显示页面上。

结构:应用程序在其展示页面上有很多评论,以及评论表。

应用视图:

<h3>Comments</h3>
<% @comments.each do |comment| %>
  <div>
    <p><%= comment.user.email %></p>
    <p><%= comment.body %></p>
    <p><%= link_to 'Delete', [@app, comment], method: :delete, data: { confirm: 'Are you sure?' } %></p>
  </div>
<% end %>
<%= render 'comments/form' %>

评论管理员:

  def create
    @app = App.find(params[:app_id])
    @comment = current_user.comments.build(params[:comment_params])
    @comment.user = current_user
    @comment.app = @app    
    @comment.save

      if @comment.save
        flash[:notice] = "Comment was added to the #{@comment.app.name}."
        redirect_to(@app)
      else
        flash[:error] = "There was a problem adding the comment."
        redirect_to(@app)
      end
  end

def comment_params
  params.require(:comment).permit(:user_id, :app_id, :body, :user_attributes => [:email])
end

在我的应用程序控制器中:

  def show
    @app = App.find(params[:id])
    @comments = @app.comments.all
    @comment = @app.comments.build
  end

def app_params
  params.require(:app).permit(:name, :brief, :description, :element, :user_attributes => [:id], :element_attributes => [:name], :elements => [:name])
end

评论表:

<%= form_for [@app, @comment] do |f| %>

  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
  <%= f.hidden_field :app_id %>
<% end %>

为什么服务器发帖不保存正文?我在这里忽略了什么?

提前致谢。

在这种情况下,您实际上根本不需要使用嵌套属性。也没有理由通过表单传递 user_idapp_id,因为它们在控制器中是已知的。这样做只会为潜在的恶作剧打开大门。点赞发送

user_id: 1, body: 'My boss is such a duchebag'

糟糕。

def create
  @app = App.find(params[:app_id])
  @comment = Comment.new(comment_params.merge(
    app: @app,
    user: current_user
  ))
  # notice that you where calling @comment.save twice..
  if @comment.save
    flash[:notice] = "Comment was added to the #{@comment.app.name}."
    redirect_to(@app)
  else
    flash[:error] = "There was a problem adding the comment."
    redirect_to(@app)
  end
end

def comment_params
  params.require(:comment).permit(:body)
end