views:

97

answers:

3

I would like to create form with text_fields

  • TITLE
  • CONTENT
  • TAGS

I have Post (TITLE, CONTENT) and Tag (TAGS) model. TAGS is a single text field. What do I have to do to save TAGS to Tag model. Let say I write 'banana, juice, new tag' in the TAGS field, how can this be parsed into array and then save in the Tag model.

Thx!

+1  A: 

Have you seen http://github.com/jviney/acts_as_taggable_on_steroids/ This should make life much easier for you.

tsdbrown
Jup... but I have complex SQLs that can not play with the plugin.
xpepermint
+1  A: 

Use a setter method in your model to do it.

Your view would look like this:

<% form_for @post :url => { :action => "update" } do |post_form| %>
  Title: <%= post_form.text_field :title %>
  Content: <%= post_form.text_field :content %>
  Tags: <%= post_form.text_field :tag_field %>
<% end %>

And then in your model you would have a model such as this:

def tag_field=(field_data)
  field_data.split.each { |tag| tags.build(:name => tag) }
end

Edit: As has been mentioned, there are plugins which do this for you, acts_as_taggable_on_steroids is a horribly named, but very effective option.

Andrew Harvey
+1  A: 

Ryan Bates has a screencast on implementing tags via a virtual attribute.

Steve Weet