Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Building Social Features in Ruby on Rails Adding State Setting Up The State Machine

Kevin Kenger
Kevin Kenger
32,834 Points

Unknown key: :conditions

I'm having trouble with setting has_many through with conditions.


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


/Users/kengers/.rvm/gems/ruby-2.1.1/gems/activesupport-4.1.0/lib/active_support/core_ext/hash/keys.rb:71:in 'block in assert_valid_keys': Unknown key: :conditions. 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 (ArgumentError)

Any help would be greatly appreciated!

Kevin Kenger
Kevin Kenger
32,834 Points

If anyone else has this problem, this should fix it:

has_many :friends, -> { where(user_friendships: { state: "accepted"}) }, through: :user_friendships
Todd Nestor
Todd Nestor
10,689 Points

Thanks for posting that, I had figured out the difference for using Rails 4, but I couldn't quite figure out how to write the user_friendships: part, I kept putting it outside of the where() statement. This got me past that part.

Kevin Kenger
Kevin Kenger
32,834 Points

Awesome! I'm glad it helped, Todd!

2 Answers

I had the same problem using Rails 4.1.4, thanks Kevin :) I also had some trouble in the next lesson where the pending_friends relationship is mapped. It can be accomplished by the following code:

  has_many :pending_friends, 
              -> { where user_friendships: { state: "pending" } }, 
                 through: :user_friendships,
                 source: :friend

What does your user model exactly look like? I can't get this to work.

Nelly Nelly
Nelly Nelly
7,134 Points
  has_many :user_friendships
  has_many :friends,-> { where(user_friendships: { state: "accepted"}) }, through: :user_friendships
  has_many :pending_user_friendships, -> { where  state: "pending"  }, class_name: 'UserFriendship', foreign_key: :user_id
  has_many :pending_friends, through: :pending_user_friendships, source: :friend

I still had failure and found out that gem"state_machines"has to come with another gem

gem 'state_machines'
gem 'state_machines-activerecord'