Matthew Boston
Matthew Boston

Reputation: 1320

Parsing blog post tags from a text_field

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!

Upvotes: 2

Views: 582

Answers (1)

farnoy
farnoy

Reputation: 7766

I understand that you're not interested in plugins, but they handle it like this: Class Post has method tag_list=, which does split(',') from the string and then searches and adds Tags from HABTM relation. You can define that Post#tag_list= with this:

def tag_list=(tags)
  self.tags.clear  # clears all the relations
  tags.split(',').each do |tag|
    self.tags << Tag.find_by_title(tag)  # and assigns once again
  end
end

To provide list of tags, ie. for form field to have existing tags, do this:

def tag_list
  self.tags.collect do |tag|
    tag.name
  end.join(',')
end

So you can now use <%= text_field_tag :post, :tag_list, :value => @post.tag_list %>.

Upvotes: 2

Related Questions