views:

58

answers:

2

I am trying to use acts_as_taggable plugin to include tag functionality in my ruby on rails application. I have attached the code. I have installed the plugin and also run the migrations.I am getting the following error.

undefined method `each' for "value of the parameter":String

Code

location.rb - location table has name, tags(this is an additional field I have in the table, I added it before knowing about the plugin :), city fields

class Location < ActiveRecord::Base
  belongs_to :profile
  acts_as_taggable
end

profile.rb

class Profile < ActiveRecord::Base
  has_many :locations
  acts_as_tagger
end

location_controller.rb

def create
  @location = Location.new(params[:location])
  @location.tag_list = ["tags1","tags2"]
  if @location.save
     redirect_to(@location)
  else
     redirect_to(@profile)
  end 
end

Application Trace

/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/associations/association_collection.rb:320:in `replace'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/associations.rb:1331:in `block in collection_accessor_methods'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/base.rb:2906:in `block in assign_attributes'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/base.rb:2902:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/base.rb:2902:in `assign_attributes'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/base.rb:2775:in `attributes='
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-2.3.8/lib/active_record/base.rb:2473:in `initialize'
/Users/felix/rails_projects/sample_app/app/controllers/locations_controller.rb:92:in `new'
/Users/felix/rails_projects/sample_app/app/controllers/locations_controller.rb:92:in `create'

Thanks

A: 

I'm guessing, since I'm not sure what the values in params are (perhaps you can output a params.inspect to get them); I think the value you passed to Location.new in params[:location] is a String and it was expecting a hash of key value pairs.

Maybe you meant: Location.new(:location => params[:location])

Or: Location.new(params)

Or maybe Location.new(params[:location]) is correct, but it is not a hash like it should be (this is usually done for you by the form helpers in your view code).

fd
+2  A: 

Are you using Ruby 1.9 by any chance? The rest of this answer is prefaced on a yes. If so read on.

You may have stumbled over a 1.9 change of behavior. Strings in 1.9 no longer support each (i.e. they are notEnumerable like Ruby 1.8). But you can use each_char which is probably what was intended.

If this isn't your code blowing up then you could either:

  • Go back to 1.8.x (Obvious)
  • Hack the String class by adding a method each (Messy and possibly dangerous)
  • Fix the gem or plugin that is causing the trouble.

There's a great article on all this here

bjg