简体   繁体   中英

rails 4.1.6 scope: in model not responding properly

Hi i am in a bit of a bind here because i am trying to use scope and cant seem to make it work.

I am now using it in my model section like so.

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

also before i was using it like so from the turorials and i found out it was depricated and had to re adjust the code that i used above but the problem is that it also encountered an error

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

this was the error that i encountered while using the first line of code and the second line of code in the terminal

/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)

if anybody can help me with this problem it would really be great and appreciated! also i am a bit of a noob in rails so i might not understand properly the syntax that you might put in the answer so can you pls. make it noob friendly and thanks!

You don't need the word scope in there. The lambda should just be given as the second argument to has_many :

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

You can see more examples in the Active Record Assocations Rails Guide .

Edit: Here's the method signature from the docs for has_many :

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

In your code:

  1. :friends is the name argument
  2. ->{ where(...) } is the scope argument
  3. { through: :user_friendships } is the options argument (but Ruby lets us omit the {} for a Hash when it's the last argument).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM