7

I'm building a rails engine which uses foreign keys in migrations.

    add_foreign_key "theblog_content_nodes",
                    "theblog_content_statuses", column: :content_status_id

From the version 4.2 rails supports foreign keys by itself but before we used foreigner gem for this. If we try to use foreigner with rails 4.2 and newer we get an error.

So since I'm going to support rails starting from 4.0.1 I have to use conditional dependency in my gemspec.

I found possible solution here but I have no idea how to check rails version in the gemspec.

# sidekiq-spy.gemspec

if RUBY_VERSION >= '2.1'
  spec.add_development_dependency "curses", "~> 1.0"
end

NOTE:

I have another temporary solution: I just check Foreigner availability in my migrations. If it is unavailable I just don't create foreign keys:

if defined?(Foreigner)
  add_foreign_key "theblog_content_nodes",
                  "theblog_content_statuses", column: :content_status_id
end

But I'd like to add foreigner dependency for old rails versions.

4

1 回答 1

2

要访问 rails 版本,我们可以使用以下内容(基于此答案):

require 'rubygems'

rails_gem = Gem::Specification.select {|z| z.name == "rails"}.max_by {|a| a.version}
p rails_gem.version.version
#=> "4.2.5"
于 2015-12-02T12:24:05.090 回答