开发者

Rails nested forms

I would like to create form with text_fields

  • TITLE
  • CONTENT
  • TAGS

I have Post (TITLE, CONT开发者_开发百科ENT) 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!


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜