【发布时间】:2017-02-27 22:29:07
【问题描述】:
我有两个相互依赖的模型,帐户和用户。账户总是由用户创建的,其 id 存储在账户的 creator_id 属性中,用户必然属于一个账户(但对属于一个账户的用户数量没有限制),该信息存储在用户的account_id 属性。同一用户可以创建不同的帐户。
我是这样表达这些规则的:
用户模型:
belongs_to :account, inverse_of: :users
has_many :created_accounts, class_name: "Account", :foreign_key => "creator_id"
帐户模型:
belongs_to :creator, class_name: 'User', optional: true
has_many :users, inverse_of: :account
由于它们是相互依赖的,我使用了一种肮脏的解决方法来实例化它们:我首先创建帐户,然后在该操作之后强制用户创建他们的个人资料,并将他们的 user_id 作为 creator_id 添加到帐户中更新。
这就是我在帐户模型中拥有的原因:
validate :require_actual_creator_id, on: :update
------------------------------------------------
def require_actual_creator_id
User.find(creator_id)
end
我正在开发一个仅涉及用户模型的身份验证系统,所以我将这些行注释掉,直到昨天我取消注释它们。
我运行 db:migrate:reset、db:seed 和 db:migrate RAILS_ENV=test 没有任何问题,这两个模型在控制台中的行为都正常,但是当涉及到夹具时(例如 testing 或 db:fixtures:load ),我收到以下错误:
NoMethodError: undefined method `id' for nil:NilClass
/home/vincent/workspace/bam-rails/test/fixtures/users.yml:16:in `get_binding'
这是一个导致问题的典型夹具,第 16 行是注释的:
michael:
id: 1
handle: Michael Example
email: michael@example.com
encrypted_password: <%= User.generate_encrypted_token('password') %>
role_id: <%= User::ADMIN %>
is_activated: true
activated_at: <%= DateTime.now %>
#account_id: <%#= Account.first.id %>
当我评论最后一行时,就没有问题了。但是,我想为我的测试加载适当的夹具,因为例如这里创建的用户无效。
我在this post 中读到,固定装置按字母顺序加载。如果这是正确的,我不明白为什么我必须评论这一行,因为帐户应该在用户之前加载。
我发现 that solution 可以工作,但它不是来自官方文档,而且它很旧,可以追溯到 2007 年。我担心这会从一天到另一天停止工作。
有谁知道如何在 Rails 5 中按自定义顺序正确加载固定装置,或者对我的问题有其他解决方案吗? 提前谢谢你。
【问题讨论】:
标签: ruby-on-rails associations ruby-on-rails-5 fixtures ruby-2.3