Justin D.
Justin D.

Reputation: 4976

Rails acts_as_taggable_on implemantation

I am trying to implemant acts_as_taggable_on in my website.

I have ran the installation setup and it worked fine. I am struggling at how to wrote the code to make it work.

The error I am getting right is the following : undefined method 'each' for "tag1, tag2, tag3":String at line 29 which is @video = Video.new(params[:video]).

Here is what I have...

Video controller

acts_as_taggable

In my form

= f.text_field :tags

In my model

@video = Video.new(params[:video])
@video.tag_list = params[:video][:tags]
if @video.save
  ...

Upvotes: 2

Views: 115

Answers (1)

deefour
deefour

Reputation: 35370

You're getting this error because you are passing params[:video] which, among other attributes, contains data for the :tags attribute in your Video model. This is a problem because it's going to use the acts_as_taggable_on's writer method for tags=, which expects an Array, not a String, unlike tag_list= which does expect a String.

One solution, keeping most of your code as is would be to remove :tags from the params and pass it to tag_list=:

tags_str = params[:video].delete(:tags)
@video   = Video.new(params[:video])
@video.tag_list = tags_str

if @video.save
  # ...

There are of course many variations on the above to get a working solution. For one, you could just give tags= what is wants, splitting :tags in params to an Array

video_params = params[:video]
video_params[:tags] = video_params[:tags].split(/\,\s*/)
@video   = Video.new(video_params)

if @video.save
  # ...

Upvotes: 3

Related Questions