【问题标题】:Automatic associations in ruby on rails fixturesruby on rails 固定装置中的自动关联
【发布时间】:2010-10-20 07:36:41
【问题描述】:

this article 中所述,我在夹具中使用自动关联。例如,如果一个区域对象有一个国家/地区 id,而不是执行“country_id”:1,我执行“country”:“USA”。 “USA”是我的 countries.yml 文件中的一个标签,所以fixtures 知道如何处理这个问题。但是,这仅在您没有为国家对象指定 ID 值时才有效。所以我不能将美国的 ID 指定为 1。但如果我不将其指定为 1,它最终会变成一个很大的值 8974343 ......这有点奇怪。有没有办法让固定装置自动生成不是超高的 id? ....或者这样可以吗?

【问题讨论】:

    标签: ruby-on-rails ruby fixtures


    【解决方案1】:

    这就是你如何获得一个自动生成的灯具标签的 ID。

    Fixtures.identify(:reginald)
    

    【讨论】:

    • 这篇 SO 文章对我帮助很大,我想对 Rails 4.1.0.rc1 进行更新:跨度>
    • 我必须包含标签所指的类。 ruby-journal.com/rails/…
    【解决方案2】:

    阅读 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.
    

    【讨论】:

    • 你认为人们为什么会接受答案但不投票?
    【解决方案3】:

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

    http://edgeapi.rubyonrails.org/classes/ActiveRecord/FixtureSet.html#class-ActiveRecord::FixtureSet-label-Fixture+label+interpolation

    在夹具标签插值下:

    monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
    pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        自动测试以强制执行夹具完整性

          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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-30
          • 2021-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-21
          相关资源
          最近更新 更多