Ruby on rails RubyonRails设备中的自动关联

Ruby on rails RubyonRails设备中的自动关联,ruby-on-rails,ruby,fixtures,Ruby On Rails,Ruby,Fixtures,如中所述,我在装置中使用自动关联。例如,如果一个region对象有一个国家id,则不执行“country_id”:1,而是执行“country”:“USA”。“USA”是my countries.yml文件中的一个标签,因此Fixture知道如何处理这个问题。但是,这仅在未为countries对象指定ID值时有效。所以我不能将USA的ID指定为1。但如果我不把它赋值为1,它会变成一个大值8974343…这有点奇怪。有没有办法让装置自动生成不是超高的id。。。。或者这可以吗?阅读API文档,这正是

如中所述,我在装置中使用自动关联。例如,如果一个region对象有一个国家id,则不执行“country_id”:1,而是执行“country”:“USA”。“USA”是my countries.yml文件中的一个标签,因此Fixture知道如何处理这个问题。但是,这仅在未为countries对象指定ID值时有效。所以我不能将USA的ID指定为1。但如果我不把它赋值为1,它会变成一个大值8974343…这有点奇怪。有没有办法让装置自动生成不是超高的id。。。。或者这可以吗?

阅读API文档,这正是自动生成的装置应该如何工作的——如果您想预先为装置指定一个特定的ID值,您可能应该自己分配它

如果不是,那么从API文档:

The generated ID for a given label is constant, so we can discover any fixture‘s ID without loading anything, as long as we know the label.

夹具的id直接来自散列其名称(这就是“只要我们知道标签,我们就可以在不加载任何内容的情况下发现任何夹具的id”)

这就是获取夹具标签的自动生成id的方式

Fixtures.identify(:reginald)

由于我没有足够的声誉发表评论,这是实际的Rails 4.1文档:

在“设备标签插值”下:

monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
monkey\u id:
海盗身份证:

自动测试以加强夹具的完整性

  class FixtureIntegrityTest < ActiveSupport::TestCase
    context "fixture integrity" do
      should "work" do
        fixtures = Dir["test/fixtures/*.yml"].map do |file|
          [file, File.basename(file).sub(/\..*/, "").singularize, YAML.load(ERB.new(File.read(file)).result)]
        end

        failures = fixtures.reject(&:last).map { |file,*| "#{file} is empty!"}

        failures = failures.presence || fixtures.map do |_, klass, content|
          content.select{ |_,fixture| fixture["id"] }.map do |name, _|
            fixtures.map do |file, _, content|
              content.select { |_,fixture| fixture[klass] == name }.map do |_, fixture|
                "#{file} uses #{klass}: #{name}, but should use the id!"
              end
            end
          end
        end.flatten.compact

        assert_equal [], failures
      end
    end
  end
类FixtureIntegrityTest为什么你认为人们会接受答案,但不会投票支持?因为这篇文章对我帮助很大,我想更新一下Rails 4.1.0.rc1:我必须包括标签上提到的类。