First off, let me start by saying, I know this exact question has been asked here before. But, it was not answered and I do not want to bring up a zombie thread from over a year ago.
Second, I’m not interested in using plugins, yes, I want to re-invent the wheel. I’m writing this blog in effort to learn RoR.
I’m trying to replicate the behavior of attaching tags to a post in my Rails app.
The posts form looks like this
<%= form_for @post do |post_form| %>
...
<%= render :partial => 'tags/form',
:locals => { :form => post_form } %>
...
<% end %>
And the tags form as follows
<%= form.fields_for :tags do |tag_form| %>
<div class="field">
<%= tag_form.label :tags, 'Tags' %> <small>(comma separated)</small><br />
<%= tag_form.text_field :tags %>
</div>
<% end %>
The problem I’m running into is, “tags” is not a field on my Post class. My Post and Tag models have HABTM relationships with PostsTagsJoinTable in between. So, somehow I need to parse the tags text field (using string.split(‘,’), and pass the resulting tag Strings into my controller, so my controller can create and associated the tags along with the new blog post.
Are my views setup correctly? What should my controllers look like? The Post.create specifically.
Thanks!
I understand that you’re not interested in plugins, but they handle it like this:
Class
Posthas methodtag_list=, which doessplit(',')from the string and then searches and addsTags from HABTM relation. You can define thatPost#tag_list=with this:To provide list of tags, ie. for form field to have existing tags, do this:
So you can now use
<%= text_field_tag :post, :tag_list, :value => @post.tag_list %>.