Reputation: 1575
I have a pretty common many-to-many association in my models, each story
has_many tags
, what I want to do is to be able to update all of the tags of the story in a simple matter. Right now I'm just deleting all relations and writing them again, basically:
def update_tags(tag_list)
self.tags.clear
tag_list.each { |tag| self.tags << tag }
save
end
But I feel that it's a dirty way to do things, as there a better solution to this issue? Something like
self.tags = tag_list
save
Although that doesn't work of course :)
EDIT: So the latter works, turns out I was building a list using map, and inside the map block I used a return statement, I removed it and it (using implicit return I guess) and it now works!
Upvotes: 0
Views: 65
Reputation: 411
Why not? http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-many-collection-objects
def update_tags(tag_list)
self.tags = tag_list
end
This must work.
Upvotes: 2