2

我是 Rails 的新手,我正在关注 Railscast #258 来实现 jQuery TokenInput,并且由于某种原因在尝试创建新记录时出现错误:

NameError: undefined local variable or method `through' for #<Class:0x101667ef0>
    from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.5/lib/active_record/base.rb:1008:in `method_missing'
    from /Users/Travis/Desktop/YourTurn/app/models/tag.rb:4
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load_file'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:596:in `new_constants_in'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:453:in `load_file'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:340:in `require_or_load'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:491:in `load_missing_constant'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:183:in `const_missing'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:181:in `each'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:181:in `const_missing'

我的标签控制器:

class TagsController < ApplicationController

def index
    @tags = Tag.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
      format.html
      format.json { render :json => @tags.map(&:attributes) }
    end
  end

  def show
    @tag = Tag.find(params[:id])
  end

  def new
    @tag = Tag.new
  end

  def create
    @tag = Tag.new(params[:tagging])
    if @tag.save
      redirect_to @tag, :notice => "Successfully created tag."
    else
      render :action => 'new'
    end
  end

标签方法:

class Tag < ActiveRecord::Base
  attr_accessible :name
  has_many :taggings
  has_many :questions, through => :taggings
end

标记方法:

class Tagging < ActiveRecord::Base
  attr_accessible :question_id, :tag_id
  belongs_to :question
  belongs_to :tag
end

方法:通过:

  has_many :taggings
  has_many :tags, :through => :taggings
  attr_reader :tag_tokens

如果我在终端并创建,tag = Tagging.new我会得到适当的条目,但不会得到我在 db migrate 中的标签名称create_tags。谁能帮我弄清楚问题是什么?如果我需要提供其他代码,我很乐意。

4

1 回答 1

4

你错过了一个冒号,这个:

class Tag < ActiveRecord::Base
  attr_accessible :name
  has_many :taggings
  has_many :questions, through => :taggings
end

应该是这样的:

class Tag < ActiveRecord::Base
  attr_accessible :name
  has_many :taggings
  has_many :questions, :through => :taggings
end

请注意,through更改为:through. Justthrough是一个变量,但:through它是一个符号,这就是构建散列通常需要的。

于 2011-07-21T01:36:04.570 回答