Creating dependent models in the same form

Hey Guys,

I just wanted to get some feedback on what I have done here and how to
improve it. As I am just starting rails, I think this would be super
helpful if any of you have time

So I have a table of songs. Each song could have multiple people One
person could be involved in multiple songs.

I therefore have a M2M relationship (Song <=> People). My join table
is called Songwriters.

When a person wants to add a new person as a songwriter on a song,
they have the option of either selecting from a drop down of the
current songwriters or entering the information to create a new person
right there in the form.

Here is my controller method that the songwriters/new action goes to:

def create
@songwriter = Songwriter.new(params[:songwriter])
@person = Person.new(params[:person]) # => To hold the potential
new person data

if new_person?  # => A new person needs to be created
  if @person.save
    @songwriter.person_id = @person.id  # => Replace the id of the

person with the new one
end
end

respond_to do |format|
  if @songwriter.save
    flash[:notice] = 'Songwriter was successfully created.'
    format.html { redirect_to(song_songwriters_path(@song)) }
    format.xml  { render :xml => @songwriter, :status

=> :created, :location => @songwriter }
else
format.html { render :action => “new” }
format.xml { render :xml => @songwriter.errors, :status
=> :unprocessable_entity }
end
end
end

def new_person?
params[:person][:first_name] || params[:person][:last_name] ||
params[:person][:person_alias]
end

So the first question is, what happens if for some reason, the new
person does not save? How do I stop the action from continuing?

Any help that you guys could offer me would be most appreciated! I
just want to be in your shoes right now!!!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs