我有这个问题,我的模型不想保存。我有一个标记的标记字段输入。对于令牌输入,我遵循以下指南:http://railscasts.com/episodes/258-token-fields
当我尝试创建一个新的konkurrancer时,得到这个错误:
NoMethodError in Admin/konkurrancersController#create
undefined method `class_name' for nil:NilClass
Rails.root: C:/Rails/konkurranceportalen
Application Trace | Framework Trace | Full Trace
app/models/konkurrancer.rb:15:in `tag_tokens='
app/controllers/admin/konkurrancers_controller.rb:48:in `new'
app/controllers/admin/konkurrancers_controller.rb:48:in `create'
http://pastie.org/1834194
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"yo7wcAQl81tx3zZpPP44ENPYzYRZLpgyYKY+HK3yFKM=",
"konkurrancer"=>{"name"=>"Vind en rejse",
"banner2"=>"asdasd",
"tracking"=>"sadasd",
"vaerdi"=>"12222",
"tid"=>"1 min",
"tag_tokens"=>"1",
"bedom"=>"2",
"kategori_id"=>"9",
"form"=>"Nyhedsbrev",
"partner"=>"Iqmedier",
"udtraekkes(3i)"=>"30",
"udtraekkes(2i)"=>"4",
"udtraekkes(1i)"=>"2011",
"udtraekkes(4i)"=>"08",
"udtraekkes(5i)"=>"26",
"arrangeor"=>"",
"note"=>""},
"commit"=>"Opret konkurrence"}
我的konkurrancer模型:
class Konkurrancer < ActiveRecord::Base
attr_accessible :name, :tag_tokens
has_many :tagsmenus
has_many :tags, :through => :tagsmenus
attr_reader :tag_tokens
def tag_tokens=(ids)
self.tag_ids = ids.split(",")
end
end
My tag model:
class Tag < ActiveRecord::Base
has_many :tagsmenus
has_many :konkurrancers, :through => :tagsmenus
has_friendly_id :name, :use_slug => true
before_save :assign_cached_slug, :unless => :cached_slug?
protected
def assign_cached_slug
self.cached_slug = self.name.gsub(/s+/, '_').gsub(/[^w-]/, '')
end
end
标签菜单模型:
class Tagsmenu < ActiveRecord::Base
end
我的控制器:
def new
@konkurrancer = Konkurrancer.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @konkurrancer }
end
end
# POST /konkurrancers
# POST /konkurrancers.xml
def create
@konkurrancer = Konkurrancer.new(params[:konkurrancer])
respond_to do |format|
if @konkurrancer.save
format.html { redirect_to(:admin_konkurrancers, :notice => 'Konkurrancer was successfully created.') }
format.xml { render :xml => :admin_konkurrancers, :status => :created, :location => @konkurrancer }
else
format.html { render :action => "new" }
format.xml { render :xml => @konkurrancer.errors, :status => :unprocessable_entity }
end
end
end
我已经创建了连接表和模型,并将关系添加到标记模型中。
您的模型有一些冲突的语句。首先定义:
attr_accessor ... :tag_tokens
之后有:
attr_reader :tag_tokens
对于第一行来说是不必要的,反之亦然,因为后面会有setter的定义:
def tag_tokens(ids)
self.tag_ids = ids.split(',')
end
我没有看到tag_ids
被定义,因为它不是你表中的一列。您可能应该为tag_tokens
删除attr_accessor
定义,然后为启动器定义tag_ids
方法。
class Tagsmenu < ActiveRecord::Base
belongs_to :konkurrancer
belongs_to :tag
end