嵌套的注释主体没有被保存在Ruby on Rails上

时间:2015-06-21 20:44:19

标签: ruby-on-rails devise nested-forms nested-attributes

我正在我的桌子上试图找出评论为什么发布comment.body,但当我进入IRB body = nil并且它不会在App show page上显示时。 / p>

结构:应用在其展示页面上有很多评论,还有评论表单。

应用视图:

<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 %>

为什么heck是服务器发布但不保存正文?我在这里俯瞰什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

在这种情况下,根本不需要使用嵌套属性。由于它们在控制器中已知,因此没有理由通过表单传递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