为什么这个named_scope会创建一个NoMethodError?

时间:2011-03-11 23:42:44

标签: ruby-on-rails named-scope ruby-on-rails-2 ruby-1.8

我没有看到此代码在哪里创建此NoMethodFound错误,并且非常想要任何有用的建议。

以下是错误消息:

NoMethodError in UploadsController#create

我模型的相关部分如下所示:

  named_scope :by_name, lambda { |marker_name| 
    {:conditions => ["marker_name = ?", marker_name]}}

  def self.parse_file(file)
    FasterCSV.foreach(file.path,:headers=>"first_row", :col_sep=>"\t") do |row|

    if $header_row == 1
       $markers = {}         # define global hash for marker id lookup
        $markers_arry = []    # define global array for marker names
        get_markers(row)
        $header_row = 0
        # done with header row; loop back to beginning for first row of actual data
        next
      end
...
 def self.get_markers(row)
    offset = 8    # this was determine by trial-&-error
    i = 0
    for col in row
      i += 1
      if i < offset
        next
      end      
      this_marker = Marker.by_name(row[col])
      $markers[row[col]] = this_marker.id   # associate the marker_name with its id
      $markers_arry[col] = row[col]
    end
  end

跟踪看起来像:

> undefined method `by_name' for
> #<Class:0xb6726e40>
> vendor/rails/activerecord/lib/active_record/base.rb:1667:in
> `method_missing'
> app/models/upload.rb:99:in
> `get_markers'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:362:in
> `each'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:362:in
> `each' app/models/upload.rb:91:in
> `get_markers'
> app/models/upload.rb:37:in
> `parse_file'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:1545:in
> `each'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:1048:in
> `foreach'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:1222:in
> `open'
> /usr/lib/ruby/gems/1.8/gems/fastercsv-1.5.4/lib/faster_csv.rb:1047:in
> `foreach' app/models/upload.rb:25:in
> `parse_file'
> app/controllers/uploads_controller.rb:55:in
> `create'
> vendor/rails/actionpack/lib/action_controller/base.rb:1162:in
> `send'

2 个答案:

答案 0 :(得分:9)

请注意,在Rails 3中,named_scope已重命名为scope

答案 1 :(得分:0)

您是否尝试过“by_name”而不是“Marker.by_name”?

此外,Rails动态生成许多类似的方法。例如,

Marker.find_by_name("your_name_here")

......无论如何都应该有效。