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控制台中运行follwing命令时的错误,但在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

最佳答案

似乎您使用的是Rails 4,它来自发行说明:



因此,对于初学者而言,您需要在模型上调用to_a。但是您确定enumerated_attribute已准备好Rails 4吗?

如果您不使用postres,我建议您只使用validates_inclusion_of,如果您使用的是postgres,请查看https://coderwall.com/p/azi3ka

关于ruby-on-rails - 记录包含enum_attr的.all时,参数数量错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18553013/

10-08 22:59