ineedahero
ineedahero

Reputation: 537

Rails Associations: belongs_to has_many confusion

I've read through the following tutorial and found the curious line:

notice that the create function is written in such a way that there has be a @post before creating a @comment.

You can see the supporting controller code:

Class CommentsController < ApplicationController
  ----
  def create
    @post = Post.find(current_post)
    @comment = @post.comments.create(post_params)  ## 'Essential stuff'
    respond_to do |format|
      if @comment.save
        format.html { redirect_to action: :index, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end 
    end
  end
  ----
end

Indeed, "current_post" implies that the post was created BEFORE the comment.

But what if I want both to be created simultaneously? For example, suppose my USER has_many EMAILS, and each EMAIL belongs_to a USER. Then, when creating a new user, I may want to have an expandable form that allows the user to add one, two, three, or twenty emails while creating his account.

How could this be done?

Upvotes: 1

Views: 61

Answers (2)

Amit Patel
Amit Patel

Reputation: 15985

Nested Attributes is the rails way of doing what you want to achieve.

Checkout http://railscasts.com/episodes/196-nested-model-form-part-1

Upvotes: 1

Gurmukh Singh
Gurmukh Singh

Reputation: 2017

You need to consider using nested form, have a look into this gem, very easy to implement. It will allow the user to add multiple emails as required.

Upvotes: 0

Related Questions