Я уже просматривал все другие стековые потоки для этой проблемы, но ни одно из решений не устранило это. Мои элементы в nested_form не сохраняются в базе данных. Я также убедился, что все ассоциации моделей верны. Я пытался исправить это в течение почти 8 часов, и был бы очень признателен за помощь, особенно учитывая, что все остальные решения не сработали.
По сути, у меня есть модель списка воспроизведения, которая содержит несколько моделей композиций. Я пытаюсь использовать nested_form для добавления моделей композиций в список воспроизведения. Тем не менее, ни одна из песен никогда не сохраняется. Я извиняюсь, если мои методы ошибочны, так как я все еще плохо знаком с Rails.
Репозиторий GitHub: 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 %>