views:

20

answers:

1

Hi there,

I have two models and controllers: Snippets, and Tags.

There is a belongs_to relationship, with tags belonging to snippets. This works well, I have a text field which creates a new tag associated with the snippet when the user submits a snippet.

I want to be able to have a text field which, when submitted to a function (in the model) would split the text on commas (e.g. split(",")).

However, I'm having a little trouble with it.

My though process was, def a function on the Snippet model that splits the input then loops the array of the split, creating a new Tag associated with the Snippet at save time.

Sounds easy enough, but with the RoR magic it's just not happening for me :)

Can someone shed some light / link to a document or something - would be grand!!

Using rails3 with ruby 1.9.2 - normally PHP dev but giving this ruby a go. Magic.

+1  A: 

There is a Railscast that explains how to use a virtual attribute in your model to convert submitted "tag_names" into associated models.

It also shows how to do a has_many :through association (called "Taggings") so that tags can belong to many snippets. In your setup, a tag can only belong to one snippet, so you would likely be creating many duplicate tags, when in fact they're the same tag, just associated to different snippets.

If you prefer reading to screencasts, you can check out the transcribed ASCIIcasts.

Andrew Vit