Overloading a model assignment to create associated models
I have a model for a Playlist object that has a number of Tracks. It's a :has_many :through, with PlaylistItem as the join table.
When the model gets created, I want to simply pass through a neat array of track_ids to create all the associated PlaylistItems (all tracks already exist). I'm exposing this as an API, so I can't really create nice forms / control the input as much.
# in PlaylistsController
@playlist = Playlist.new :some_attr => "ABCDE", :playlist => ["123","22","11"]
What i'm trying to do is create a cu开发者_运维技巧stom assignment method like this:
class Playlist < ActiveRecord::Base
...
def playlist=(track_array)
track_array.each do |track_id|
# check for valid track_id, add info to errors if something's wrong
# for valid tracks, add it to playlist_items
playlist_items.create(:track_id => track_id)
end
end
Since I use create instead of new here, it's an error because the current Playlist item being created doesn't have an ID yet.I'm going to stick to deleting the key and doing all this in the controller for now, but I'm sure there's gotta be some way to achieve this neat assignment trick. Any thoughts?
Update
I just found a solution:
playlist_items << playlist_items.new(:track_id => track_id)
Seems to be working. Should've thought of assigning it back to the Playlist object properties and using new earlier...
You can try to use the inbuilt assignments:
class Playlist < ActiveRecord::Base
...
def playlist=(track_array)
self.track_ids = track_array.select do |track_id|
# check for valid track_id, add info to errors if something's wrong
# for valid tracks, return true
end
end
...
end
精彩评论