6

一个 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 中查询这样的种子时(这是我在 ruby​​mine 控制台中运行以下命令时出现的错误,但是在 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

4

1 回答 1

1

似乎您正在使用发行说明中的​​ Rails 4:

Model.all 现在返回一个 ActiveRecord::Relation,而不是一个记录数组。如果你真的想要一个数组,请使用 Relation#to_a。在某些特定情况下,这可能会导致升级时损坏。

因此,对于初学者,您需要调用to_a模型。但是你确定 enumerated_attribute 准备好 rails 4 了吗?

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

于 2013-09-25T11:27:50.897 回答