开发者

Form is submitting when the page loads

I have a really simple Rails app. Basically an article with comments. I want the article page to show the article, comments underneath and then a textbox to write a comment and a submit button to submit it.

I got it all working except for one (big) problem. When the page loads.. example.com/article/1 a blank comment is submitted to the database.

I fixed that by including "validates_presence_of :body" in the Comment model. But that results in the following image when the page loads:

Form is submitting when the page loads

This is my code by the way:

def show
@place = Article.find(params[:id])
@comment = Article.find(params[:id]).comments.create(params[:comment])

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @article }
end
开发者_如何学C  end

and

    <% form_for([@article, @comment]) do |f| %>
  <p>
    <%= f.label :commenter %><br />
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>

  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>


It's because you made a create.

Create try save object and like is invalid, an error is generate.

Made : @comment = Article.find(params[:id]).comments.build(params[:comment])

Fix your problem I think

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜