Working with additional attribute of has_many :through associative model

155 Views Asked by At

I've got the following model relations:

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

Now what I'm interested in is changing the track_number through the playlist. I finally managed to access the track numbers via i.e. playlist.songs[1].track_number thanks to this reply. However, when trying to change the value that way in the console, it wasn't written back to the actual song_in_playlist object. Do you know how this is achievable?

Furthermore, how would a correct update parameter look like? Would it be like this then:

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

edit: This is what I tried in the console

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
[...]
0

There are 0 best solutions below