Shane
Shane

Reputation: 5677

How rails form instance works?

I have these two methods, show and create.

def show
    @article = Article.find(params[:id])
    @comment = Comment.new
    @comment.article_id = @article.id
end

def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:article_id]
    @comment.save
    redirect_to article_path(@comment.article)
end

Show method displays my comment form.

In the show method why do we create a new instance of Comment and also associate the comment instance to an article id.

Create method actually handles the submission of form.

In the create method, again i am creating a new comment object and again associating the comment's article_id.

My whole questing is why were repeating these things?. Why do I have associate my comment form with article_id when I am displaying it and again I am repeating the steps while submitting the form too.

Upvotes: 0

Views: 50

Answers (2)

DaveMongoose
DaveMongoose

Reputation: 905

The reason that you initialize a comment both times is because the user's browser only sees the html form - it doesn't have a concept of a Comment - and because each request to a Rails application is independent - nothing is persisted in the application between requests:

When the user requests the show page for an Article, the request is handled by the application something like this:

  1. The controller creates a new Comment object (in memory).
  2. The form_for helpers in the view build a form from that Comment.
  3. The html for the show page is sent to the user's browser.

At this point the application has done everything it needs to serve this request, so the temporary Comment object is deleted.

When the user submits the form, the values that were entered are sent to the application in the comment_params and the application handles this request like this:

  1. The controller creates a new Comment object (again in memory), but initializes it with the data that the user sent through in comment_params.
  2. The controller saves the Comment - this stores the Comment in the database so it can be loaded later.
  3. The controller redirects back to the show page.

Saving to the database is the main way that the application can persist things between requests - objects in memory only exist while the request is being processed.

Upvotes: 1

Himesh
Himesh

Reputation: 646

This repetition could be avoided if you keep those resources nested and build the form as:

<%= form_for(@article, @article.comments.build) do |f| %>

Hope this helps! :)

Upvotes: 2

Related Questions