vendredi 2 septembre 2016

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?

Aucun commentaire:

Enregistrer un commentaire