如何运行Internet上共享的Rails片段

时间:2018-12-05 14:09:37

标签: ruby-on-rails

我正在尝试复制rails bug

我有一个rails snippet,但是我不知道如何运行它。

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "activerecord", "5.1.6"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.integer :company_id, index: true, foreign_key: true
  end

  create_table :companies, force: true do |t|
  end
end

class Company < ActiveRecord::Base
  has_many :users, inverse_of: :company
end

class User < ActiveRecord::Base
  belongs_to :company, inverse_of: :users
end

class BugTest < Minitest::Test
  def test_pluck
    company = Company.create
    user = company.users.create

    assert_equal [[user.id, company.id]], User.where(company_id: company.id).includes(:company).pluck(:id, :'companies.id')
  end
end

如何在本地测试此代码段?

我应该将其放入.rb文件中并与ruby一起运行吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下命令从终端运行ruby文件:

ruby path/to/ruby_file.rb

但是,您上面给出的代码片段实际上并没有做什么,据我所知,它只是设置了准备使用它们进行处理的类。

在查看了错误链接之后,您将需要创建一个新的Rails应用程序(只需从控制台尝试rails new project_name),然后按照代码段中的描述设置模型。