I have some users that can have many posts, and each of those posts can have many tags. I\'ve implemented that using a
My preference would be to create an attribute on the post.model to read in the tags. e.g.
app/models/post.rb
def tag_list
self.tags.map { |t| t.name }.join(", ")
end
def tag_list=(new_value)
tag_names = new_value.split(/,\s+/)
self.tags = tag_names.map { |name| Tag.where('name = ?', name).first or Tag.create(:name => name) }
end
Then in your view you can do:
<%= f.text_field :tag_list %>
instead of :tags
The post model will accept the tag list, split into tag names, find the tag if it exists, and create it if it doesn't. No controller logic required.
EDIT This code of course relies on your tag model having an attribute called name (if not just substitute whatever attribute you're storing the tags 'name' in), and that it's unique in the database (i.e. you're using something like validates_uniqueness_of :name
in your tags model)