1

我有以下模型关系:

class Song < ActiveRecord::Base
  has_many :song_in_playlists, :dependent => :destroy
  has_many :playlists, :through => :song_in_playlists
  attr_accessible :song_in_playlists_attributes
  accepts_nested_attributes_for :song_in_playlists

class Playlist < ActiveRecord::Base
  has_many :song_in_playlists, :dependent => :destroy
  has_many :songs, :through => :song_in_playlists, :select => 'songs.*, song_in_playlists.track_number as track_number'
  attr_accessible :song_in_playlists_attributes
  accepts_nested_attributes_for :song_in_playlists, :reject_if => :all_blank, :allow_destroy => :true

class SongInPlaylist < ActiveRecord::Base
  belongs_to :playlist
  belongs_to :song
  accepts_nested_attributes_for :song, :reject_if => all_blank
  attr_accessible :track_number, :song_attributes

现在我感兴趣的是track_number通过播放列表更改。playlist.songs[1].track_number多亏了这个回复,我终于设法通过 ie 访问了曲目编号。但是,当尝试在控制台中以这种方式更改值时,它并没有写回实际song_in_playlist对象。你知道这是如何实现的吗?

此外,正确的更新参数是什么样的?那么会不会是这样:

playlist["id"] = 1
playlist["songs"] = [{"song_id" = 3, "track_number" = 1}, {"song_id" = 2, "track_number" = 2}]

编辑:这是我在控制台中尝试过的

irb(main):025:0> p.songs[1].track_number = 1
=> 1
irb(main):026:0> p.songs[1].save
   (0.5ms)  begin transaction
  Song Exists (0.8ms)  SELECT 1 AS one FROM "songs" WHERE ("songs"."dropbox_path" = '/audiomixer/03 - As It Is When It Was.mp3' AND "songs"."id" != 3 AND "songs"."user_id" = 1) LIMIT 1
   (0.1ms)  commit transaction
=> true
irb(main):027:0> p.song_in_playlists[1]
=> #<SongInPlaylist id: 2, playlist_id: 1, song_id: 3, track_number: nil, created_at: "2013-08-13 18:00:03", updated_at: "2013-08-13 18:00:03">

irb(main):004:0> p.songs[1].update_attributes(:track_number => 1)
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: track_number
[...]
4

0 回答 0