【问题标题】:why the method column_types is undefined in Rails 5.0?为什么 Rails 5.0 中未定义 column_types 方法?
【发布时间】:2016-12-11 14:34:48
【问题描述】:

我正在为一个类做作业,它在 rspec 测试中使用 column_types 方法。

  it "User database structure in place" do
        expect(User.column_names).to include "password_digest", "username"
        expect(User.column_types["username"].type).to eq :string
        expect(User.column_types["password_digest"].type).to eq :string
        expect(User.column_types["created_at"].type).to eq :datetime
        expect(User.column_types["updated_at"].type).to eq :datetime

结束

错误:当我在命令行中运行 rpsec 时。
Rails 5.0
Ubuntu 14.10

失败/错误:expect(User.column_types["username"].type).to eq :string

 NoMethodError:
   undefined method `column_types' for #<Class:0x000000053a0188>
   Did you mean?  columns
                  column_names
 # ./spec/assignment_spec.rb:67:in `block (5 levels) in <top (required)>'
 # ./spec/assignment_spec.rb:14:in `block (2 levels) in <top (required)>'

【问题讨论】:

  • @ArupRakshit class User &lt; ApplicationRecord end

标签: ruby-on-rails ruby rspec ruby-on-rails-5


【解决方案1】:

该方法已在 this commit 中删除。找到它并不容易。

但是,原因是没有记录,这是因为方法本身没有记录(也许它只是供内部使用)。

查看this comment:nodoc:的方法,当它存在时:

def column_types # :nodoc:
    @column_types ||= columns_hash.transform_values(&:cast_type).tap do |h|
      h.default = Type::Value.new
    end
  end

您可以通读commit's 的说明以了解原因,也许看看您是否还有其他可以做的事情。

编辑

看看these lines也许attributes_typescolumns_hash可以解决你的问题。

【讨论】:

  • 使用attributes_types 对我来说效果很好。谢谢!
【解决方案2】:

您可以使用它来获取所有 column_types 的哈希

User.columns_hash.each_with_object({}) { |obj, h| h[obj[1].name] = obj[1].sql_type }

【讨论】:

    【解决方案3】:

    Rails 5 中删除了 column_types 方法。

    要获取列的类型,您可以尝试以下代码:

    User.column_for_attribute('username').type
    

    这将返回类型,在您的情况下为::string

    【讨论】:

      【解决方案4】:

      看起来像在 rails 5 中,column_types 方法不再存在

      【讨论】:

      • 如何计算出来的?我用谷歌搜索并没有说什么。是否有网站可以检查方法和弃用?
      • 是的,没有人提到它edgeguides.rubyonrails.org/… 这里.. -_-
      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多