【问题标题】:Why does id value change when referring fixtures in rails为什么在rails中引用fixture时id值会改变
【发布时间】:2016-09-27 19:46:03
【问题描述】:

我有以下固定装置。

users.yml

first_user:
  name: User1
  password_hash: <%= BCrypt::Engine.hash_secret('password', '$2a$10$xKPXy2QabH6ThBjo7gNB8O') %>
  password_salt: $2a$10$xKPXy2QabH6ThBjo7gNB8O
  role: 1

stores.yml
one:
  name: MyFirstString
  user_id: <%= ActiveRecord::FixtureSet.identify(:first_user) %>

但是,当我加载Store.first.user_id 时,我得到的值为979462526,而User.first.id980190962。我认为这些值不应该不同。请纠正我的理解或指出我的代码中的错误(如果有)。模型结构是:一个用户有很多店铺。

【问题讨论】:

  • 显然等于 979462526。

标签: ruby-on-rails ruby fixtures


【解决方案1】:

我认为ActiveRecord::FixtureSet.identify(:first_user)first_user 夹具本身无关。
source code

根据评论,它只是为给定标签生成标识符。在你的情况下,它是:first_user

所以你可以直接打开rails console 手动操作

Zlib.crc32('first_user') % (2 ** 30 - 1) 
# => 979462526

您将获得相同的数字。
所以它与任何特定的灯具无关(因为我没有任何灯具)。

更新

也许您应该尝试使用关联而不是直接链接 ID。

# users.yml
first_user:
  name: User1
  ...

# stores.yml
one:
  name: MyFirstString
  user: first_user

这样我希望它应该像预期的那样工作。

【讨论】:

  • 有趣。感谢您的解释。这个想法是在stores.yml 中引用用户对象的id 值。你知道怎么做吗?
  • 我平时不怎么用灯具,给我点时间看看吧。
  • 当然。如果您可以添加它,那将非常有帮助。
  • 读过这个guide关联的标签引用(belongs_to、has_one、has_many)部分。我会更新我的答案,不确定它是否有效,但你可以尝试一下
猜你喜欢
  • 2020-07-21
  • 2014-11-04
  • 2023-04-07
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
相关资源
最近更新 更多