2

我正在尝试使用acts_as_taggable 插件在我的ruby on rails 应用程序中包含标签功能。我附上了代码。我已经安装了插件并运行了迁移。我收到以下错误。

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

代码

location.rb - 位置表有名称、标签(这是我在表中的一个附加字段,我在了解插件之前添加了它:)、城市字段

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

配置文件.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

应用程序跟踪

/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'

谢谢

4

4 回答 4

3

您是否有机会使用 Ruby 1.9?这个答案的其余部分以“是”开头。如果是这样,请继续阅读。

您可能偶然发现了 1.9 的行为变化。1.9 中的字符串不再支持each(即它们Enumerable不像 Ruby 1.8)。但是您可以使用each_char这可能是预期的。

如果这不是您的代码爆炸,那么您可以:

  • 回到 1.8.x(很明显)
  • 通过添加方法来破解 String 类each(混乱且可能很危险)
  • 修复导致问题的 gem 或插件。

这里有一篇很棒的文章

于 2010-07-20T21:54:25.357 回答
0

我猜,因为我不确定 params 中的值是什么(也许你可以输出 aparams.inspect来获取它们);我认为您在 params[:location] 中传递给 Location.new 的值是一个字符串,它期待键值对的散列。

也许你的意思是:Location.new(:location => params[:location])

或者:Location.new(params)

或者也许Location.new(params[:location]) 是正确的,但它不是应有的散列(这通常由您的视图代码中的表单助手为您完成)。

于 2010-07-20T21:47:40.537 回答
0

我有一个类似的问题,acts_as_taggable 抱怨一个未定义的每个方法,问题是我的视图 _form 中有错误的字段。我有:

<%= f.text_field :tags %>

而不是它应该是什么:

<%= f.text_field :tag_list %>
于 2012-04-04T21:09:54.647 回答
0

尝试替换@location.tag_list = ["tags1","tags2"]

@location.tag_list = "tags1, tags2"

你也可以像这样添加标签

@location.tag_list.add("tag1, tag2", parse: true)

查看此演员表以获取更多信息

于 2015-07-17T13:28:21.567 回答