我是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'
My Tags controller:
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
方法with:through:
has_many :taggings
has_many :tags, :through => :taggings
attr_reader :tag_tokens
如果我在终端中创建tag = Tagging.new
,我得到适当的条目,但不是我在db迁移create_tags
中的标记名称。谁能帮我弄清楚是什么问题吗?如果我需要提供其他代码,我很乐意。
你少了一个冒号,这:
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
。只有through
是一个变量,但:through
是一个符号,这是你通常想要的构建哈希