一个 MODEL1 有一个 account_type,所以使用 gem 'enumerated_attributes',我制作了这样的模型:
class MODEL1 < ActiveRecord::Base
enum_attr :account_type, %w(^live demo disabled)
def is_live?
self.account_type == :live
end
def is_not_live?
self.account_type == :demo || self.account_type == :disabled
end
end
我不明白的奇怪的事情是,当我在任意 MODEL1 中查询这样的种子时(这是我在 rubymine 控制台中运行以下命令时出现的错误,但是在 rake db:seed 期间发生了同样的 2 for 1 错误) :
MODEL1.all.sample
和
MODEL1.all
我明白了:
Dealer Load (0.3ms) SELECT "MODEL1".* FROM "MODEL1S"
ArgumentError: wrong number of arguments (2 for 1)
from /.rvm/gems/ruby-2.0.0-p0@web/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/integrations/active_record.rb:78:in `instantiate'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/querying.rb:45:in `block in find_by_sql'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/result.rb:21:in `block in each'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/result.rb:21:in `each'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/result.rb:21:in `each'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/querying.rb:45:in `map'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/querying.rb:45:in `find_by_sql'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/relation.rb:585:in `exec_queries'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/relation.rb:471:in `load'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/relation.rb:220:in `to_a'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/activerecord-4.0.0/lib/active_record/relation/delegation.rb:49:in `sample'
from (irb):7
from /.rvm/gems/ruby-2.0.0-p0@web/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /.rvm/gems/ruby-2.0.0-p0@web/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
我试图播种的模型(在 rake db:seed 期间发生错误)是这样的:
model2 = Fabricate(:MODEL2, name: "Any MODEL2 Name #{n}", cost: n, MODEL1: MODEL1.all.sample)
在 MODEL2 模型中
belongs_to :MODEL1
在 MODEL1 模型中
has_many :MODEL2s
在迁移中,MODEL2
t.references :MODEL1
在迁移中,MODEL1
t.enum :account_type
如果有更简单的方法来为 MODEL1 指定 account_types,请告诉我,我只需要能够说 MODEL1.all.sample 或 MODEL1.all