Rails嵌套表单属性未保存

时间:2018-04-29 02:27:02

标签: ruby-on-rails

我已经查看了此问题的所有其他stackoverflow,但没有一个解决方案已修复此问题。我在nested_form中的元素没有保存在数据库中。我还确保所有模型关联都是正确的。我现在已经尝试解决这个问题近8个小时了,非常感谢一些帮助,特别是考虑到其他所有解决方案都没有起作用。

基本上,我有一个包含多个Song模型的播放列表模型。我试图使用nested_form将Song模型添加到播放列表中。然而,没有一首歌被保存。如果我的方法是错误的,我很抱歉,因为我对Rails还不太新。

GitHub回购:https://github.com/nsalesky/Ultra-Music

playlists_controller.rb

  event.waitUntil(
      event.respondWith(new Response('test', {headers: {'Content-Type': 'text/html; 
      charset=utf-8'}}))
  )

playlist.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

_form.html.erb

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

1 个答案:

答案 0 :(得分:1)

在你的playlist.rb中,你写道:

:reject_if => lambda { |a| a[:content].blank? }

这里,块参数|a|代表特定歌曲的属性。因此a[:attribute]与单个属性相关。问题是您的Song没有:content属性。因此a[:content].blank?始终为true,意味着您将被拒绝制作一首歌。

只需将a[:content]更改为有效的属性,例如a[:name]