rails 4.1.6范围:在模型中没有正确响应

时间:2014-12-31 19:44:27

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

嗨,我在这里有点绑定,因为我正在尝试使用范围而且似乎无法使其正常工作。

我现在正在我的模型部分中使用它。

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中有点像菜鸟,所以我可能无法正确理解你可能会在答案中使用的语法,所以你能不能这样做。让它非常友好,谢谢!

1 个答案:

答案 0 :(得分:3)

你不需要scope这个词。 lambda应该只作为has_many的第二个参数:

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

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

修改:以下是docs for has_many的方法签名:

  

has_many(name, scope = nil, options = {}, &extension)

在您的代码中:

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