0
我的一个模型中有一个NoMethodError问题。Mongo + RoR模型。卡住了NoMethodError
在日志文件中,我们有:
NoMethodError (undefined method `length=' for #<Book:0x000000083866b8>):
2013-03-28T10:25:19+00:00 app[web.1]: app/models/engine/book.rb:13:in `block in find_or_create_by_guide'
2013-03-28T10:25:19+00:00 app[web.1]: app/models/engine/book.rb:9:in `find_or_create_by_guide'
让我经历的所有重要的文件。
一开始,我们有蒙戈的document.rb:
class Guide::Document
include MongoMapper::Document
key :city, Integer
key :trips, Array
key :themes, Array
key :places, Array
key :pace, String
key :date_from, Time
key :date_to, Time
key :host, String
key :length, Integer
timestamps!
end
然后,在本书模型时的指导性文件名为:
module ClassMethods
def find_or_create_by_guide(guide)
book = ::Book.find_or_create_by_document(guide.id.to_s) do |b|
b.city_id = guide.city
b.host = guide.host
b.pace = guide.pace || :normal
b.length = guide.length
end
在book.rb后,我有下面一行:
groups = sorted_points.in_groups_of(self.length.count, false)
Length.rb
:
class Length < ActiveRecord::Base
belongs_to :book
attr_accessible :book_id
end
Book.rb
:
attr_accessible :user_id, :country_id, :city_id, :hotel_id, :type, :price, :host, :pace, :created_at, :updated_at, :length
最后,长度的迁移:
class AddLengthColumnToBooks < ActiveRecord::Migration
def change
add_column :books, :length, :integer
end
end
任何提示或提示理解。
我完全是开发的基础,所以我尝试从各个角度来解决这个问题。根据你写的内容,我会: 1)删除长度模型。 2)将attr_accessor:length添加到Book.rb 3)然后删除b.length = guide.length,并简单地使用self调用长度。当我需要它时(比如在groups = sorted_points.in_groups_of(self.length.count,false)) – rhjs 2013-03-28 11:38:53
1)是; 2)不,你在迁移中添加了'legth'列,所以你不需要attr_accessor; 3)b.length = guide.length似乎没问题,你不能只调用self.length,因为ClassMethods里面的'self'不是Book实例 – cthulhu 2013-03-28 12:01:05
好吧,如果我离开b.length = guide.length,那么会'groups = sorted_points.in_groups_of(self.length.count,false)'是一个正确的方法来划分sorted_points?最后一个问题:如果长度本身是一个整数,self.length实际上需要'count'吗? – rhjs 2013-03-28 12:19:52