Reputation: 2381
I'm having some difficulty creating nested objects between a one-to-many relationship. My models are Artist and Song, an artist can have many songs and a song must belong to an artist.
Where I'm having issues is creating artists and songs. For the user experience, I want users to create artist's songs at the same time they are creating the artist, so my Artist controller looks like so:
def new
@artist = Artist.new
@artist.songs.build
end
def create
@artist = Artist.new(params[:artist])
if @artist.save
redirect_to root_path
else
render :action => 'new'
end
end
and then the form:
<div>
<%= f.label :name, "Artist" %>
<%= f.text_field :name %>
</div>
<%= f.fields_for :songs do |song| %>
<div>
<%= song.label :title, "Song" %>
<%= song.text_field :title %>
</div>
<% end %>
On my Artist model, I'm currently validating uniqueness of the name, and I want to continue to do so. What I'm trying to figure out, is to find a way that if the user goes to this form, an artist with that name already exist, to ignore saving the artist, but instead to something like this:
@artist = Artist.find_by_name(params[:artist_name])
@song = @artist.songs.new
Where the new song is created for the exist artist. I can do this now by adding a link, and using my Song controller/views. I'm confused at how I could do this without a user input, and simply build the songs.
Should I be using Javascript to submit a post request if the artist name exists with the song information? I could also add logic to the controller, but don't know how to add conditions based off validation in the controller, this also smells pretty bad to me. Does anyone have any experience with a similar situation? Appreciate the help.
Upvotes: 0
Views: 176
Reputation: 2136
You're wielding a fairly scary sword, here. When validating by an artist name, can you be sure that the song might not be for a different artist of the same name? Because if your project is broad, inevitably you're going to cross-wire data.
What I would recommend is to not check this after the fact -- but, rather, when users are typing in an artist's name, to use a jQuery autocomplete plugin like http://jqueryui.com/demos/autocomplete/ so that a user can choose that artist if they are already there.
If the person types in an artist's name and that artist does exist already (using find_by_name is fine), then I'd redirect them to an intermediary page with a notice that says: "There is already an artist with that name. Is this the artist you're looking for?" with some basic info from the artist found in your database. Then you can have 2 links: one that says "Yes" and assists in the create, and one that says "No, create a new artist" and goes from there.
You should be able to do all of this with rails and not need any ajax posting, from my point of view. Make sure you're watching the params being passed from page to page. using redirect
or render
changes that.
Upvotes: 1