views:

111

answers:

2

I have an Entry model which has_many :tags. I want to be able to list my tags in an text input (ie. "tag-1, tag-2", etc.), however, I am running into an issue.

If I just use

form_for(:entry, form_options) do |f|
  f.text_field :tags
end

My text box gets created, but is filled with something like #<Tag:0xb79fb584>#<Tag:0xb79faddc>, which is obviously not what I'm looking for.

I know I can add a to_s method to Tag:

class Tag < ActiveRecord::Base
  def to_s
    name # the name of the tag
  end
end

But that just leaves me with something like tag-1tag-2 because @entry.tags.to_s still just refers to Array#to_s.

Right now, I am using

f.text_field :tags, :value => @entry.tags.map(&:name).join(", ")

instead, which will display the correct string, but doesn't feel like the "rails way" of doing things. Is there a way I can add a custom to_s method specifically to my tags association?

+1  A: 

kind of hacky and terrible, but you could

alias_method_chain :tags, :fancy_to_s
def tags_with_fancy_to_s
  assoc = tags_without_fancy_to_s
  def assoc.to_s; map(&:name).join(", "); end
  assoc
end

that should work.

Alternatively, you could just create the method "tags_string" and have it do the same thing without abusing the object system/the maintenance coders' brains.

Ben Hughes
I'm the maintenance coder (it's a personal project), so I'm not worried about that ;). I considered just adding a `tag_names` method, but the tradeoff for that is that then I need extra code in the controller to set @entry.tags for saving.
Daniel Vandersluis
false, define a tags_string= on the model (where it belongs) and have that handle the find or create by name standard tag stuff. Even better, you can use acts_as_taggable_on_steroids or similar and get this all for free.
Ben Hughes
+1  A: 

There's a better way to do this: virtual attributes. This example shows exactly how to deal with tag association using a virtual attribute.

Simone Carletti