Rails有很多对很多令牌字段的帮助

时间:2011-04-26 06:45:20

标签: ruby-on-rails ruby ruby-on-rails-3

我遇到了我的模特不想保存的问题。我有标签的令牌字段输入。 我已按照本指南进行令牌输入: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

我的标签型号:

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

我的tagmenu模型:

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

我创建了连接表和模型,并且还添加了与标记模型的关系。

2 个答案:

答案 0 :(得分:0)

您的模型有一些相互矛盾的陈述。您首先定义:

attr_accessor ... :tag_tokens

然后有:

attr_reader :tag_tokens

这对于第一行是不必要的,反之亦然,因为稍后您对setter有一个定义:

def tag_tokens(ids)
  self.tag_ids = ids.split(',')
end

我没有看到tag_ids定义,因为它不是表格中的列。您应该删除attr_accessor的{​​{1}}定义,然后为初学者定义tag_tokens方法。

答案 1 :(得分:0)

class Tagsmenu < ActiveRecord::Base
  belongs_to :konkurrancer
  belongs_to :tag
end