I've already looked through every other stackoverflow for this issue, but none of the solutions have fixed this. My elements in a nested_form are not being saved in the database. I've also made sure that all model associations are correct. I've been trying to fix this for nearly 8 hours now, and would really appreciate some help, especially considering every other solution hasn't worked.
Basically, I have a Playlist model that contains multiple Song models. I'm trying to use a nested_form to add the Song models to the Playlist. However, none of the Songs are ever being saved. I apologize if my methods are misguides, as I'm still fairly new to Rails.
GitHub Repo:https://github.com/nsalesky/Ultra-Music
playlists_controller.rb
def index
@user = current_user
@playlists = @user.playlists
end
def show
@user = current_user
@playlist = @user.playlists.find(params[:id])
end
def new
@playlist = Playlist.new
#I was told to do this
@playlist.songs.build
end
def create
@user = current_user
@playlist = @user.playlists.create(playlist_params)
if @playlist.save
redirect_to @playlist
else
render :action => 'new'
end
end
def edit
@playlist = current_user.playlists.find(params[:id])
end
def update
@user = current_user
@playlist = @user.playlists.find(params[:id])
if @playlist.update_attributes(playlist_params)
redirect_to @playlist
else
render :action => 'edit'
end
end
def destroy
@user = current_user
@playlist = @user.playlists.find(params[:id])
@playlist.destroy
redirect_to playlists_path(@user.playlists)
end
private
def playlist_params
params.require(:playlist).permit(:name, :description, songs_attributes: [:id, :name, :link, :_destroy])
end
playlist.rb
belongs_to :user
has_many :songs, dependent: :destroy
accepts_nested_attributes_for :songs, :allow_destroy => true, :reject_if => lambda { |a| a[:content].blank? }
validates :name, presence: true
validates_associated :songs, presence: true
_form.html.erb
<%= nested_form_for @playlist do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<!--<div>
<button type="button" id="addsong">Add Song</button><br>
<button type="button" id="removesong">Remove Song</button><br>
</div> !-->
<div>
<%= f.fields_for :songs do |song_form| %>
<%= song_form.text_field :name %>
<%= song_form.text_field :link %>
<%= song_form.link_to_remove "Remove Song" %>
<% end %>
<p><%= f.link_to_add "Add Song", :songs %></p>
</div>
<div>
<%= f.submit %>
</div>
<% end %>