【问题标题】:rails 4.1.6 scope: in model not responding properlyrails 4.1.6 范围:在模型中没有正确响应
【发布时间】:2014-12-31 19:44:26
【问题描述】:

您好,我在这里有点困惑,因为我正在尝试使用范围,但似乎无法使其工作。

我现在像这样在我的模型部分使用它。

has_many :friends, through: :user_friendships,
                    scope -> {where(user_friendships: { state: 'accepted' })}

在我像这样从 turorials 中使用它之前,我发现它已被贬低,不得不重新调整我上面使用的代码,但问题是它也遇到了错误

has_many :friends, through: :user_friendships,
                conditions: { user_friendships: { state: 'accepted' }}

这是我在终端使用第一行代码和第二行代码时遇到的错误

/home/simplybel/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.6/lib/active_support/core_ext/hash/keys.rb:71:in `block in assert_valid_keys': Unknown key: :scope. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table (ArgumentError)

如果有人可以帮助我解决这个问题,那将非常感谢!我也是rails中的菜鸟,所以我可能无法正确理解您可能在答案中输入的语法,所以请您帮忙。让它对菜鸟友好,谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4.1


    【解决方案1】:

    那里不需要scope 这个词。 lambda 应该作为has_many 的第二个参数给出:

    has_many :friends, ->{ where(user_friendships: { state: 'accepted' }) },
                       through: :user_friendships
    

    您可以在Active Record Assocations Rails Guide 中查看更多示例。

    编辑:这是来自docs for has_many的方法签名:

    <strong>has_many</strong>(name, scope = nil, options = {}, &amp;extension)

    在您的代码中:

    1. :friendsname 参数
    2. -&gt;{ where(...) }scope 参数
    3. { through: :user_friendships }options 参数(但是当它是最后一个参数时,Ruby 允许我们省略 Hash 的 {})。

    【讨论】:

    • 嗨,感谢您的修复,它现在可以正常工作,现在尝试执行此条件:{ state: 'pending' } 并尝试像您这样的答案:has_many :pending_user_friendships,class_name: 'UserFriendship', foreign_key: :user_id, ->{ where(user_id: { state: 'pending'})} 显然它也没有像我预期的那样工作
    • 就像我说的,lambda(-&gt;{ ... } 位)必须是第二个参数,即在:pending_user_friendships 之后和class_name: ... 之前。
    猜你喜欢
    • 2012-12-28
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多