Jake
Jake

Reputation: 1186

Difference between these creation methods? Ruby on Rails

I have a blog where I am creating comments via the following code. I noticed both work in the (seemingly) exact same manner.

Are there any pros and cons to the following two ways of calling this creation method in the view? Are there more ways available to call on such an event?

Post and Comment are connected via has_many and belongs_to relations.

  1. <%= simple_form_for([@post, Comment.new]) do |f| %>

  2. <%= simple_form_for([@post, @post.comments.build]) do |f| %>

Here is my comments_controller:

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  if @comment.save
    flash[:success] = "Comment created!"
    redirect_to post_path(@post)
  else
    flash[:danger] = "Error"
    redirect_to post_path(@post)
  end
end

Upvotes: 1

Views: 50

Answers (1)

Beartech
Beartech

Reputation: 6411

Well there is no real difference between .new and .build because build is an alias for new.

You could also put the build or new in your new controller action:

def new
  @post = Post.new
  @comment = @post.comment.build
end

And then just use the instance variables in your form:

<%= simple_form_for([@post, @comment]) do |f| %>

Upvotes: 2

Related Questions