I might be doing this wrong overall, but maybe someone will be able to chirp in and help out.
Problem:
I want to be able to build a relationship on an unsaved Object, such that this would work:
v = Video.new
v.title = "New Video"
v.actors.build(:name => "Jonny Depp")
v.save!
To add to this, these will be generated through a custom method, which I’m attempting to modify to work, that does the following:
v = Video.new
v.title = "Interesting cast..."
v.actors_list = "Jonny Depp, Clint Eastwood, Rick Moranis"
v.save
This method looks like this in video.rb
def actors_list=value
#Clear for existing videos
self.actors.clear
value.split(',').each do |actorname|
if existing = Actor.find_by_name(actorname.strip)
self.actors << existing
else
self.actors.build(:name => actorname.strip)
end
end
end
What I expect
v.actors.map(&:name)
=> ["Jonny Depp", "Clint Eastwood", "Rick Moranis"]
Unfortunatey, these tactics neither create an Actor nor the association. Oh yeah, you might ask me for that:
in video.rb
has_many :actor_on_videos
has_many :actors, :through => :actor_on_videos
accepts_nested_attributes_for :actors
I’ve also tried modifying the actors_list= method as such:
def actors_list=value
#Clear for existing videos
self.actors.clear
value.split(',').each do |actorname|
if existing = Actor.find_by_name(actorname.strip)
self.actors << existing
else
self.actors << Actor.create!(:name => actorname.strip)
end
end
end
And it creates the Actor, but I’d rather not create the Actor if the Video fails on saving.
So am I approaching this wrong? Or have I missed something obvious?
Try this: