Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown key in Rails association

I have the following associations code:

has_many :rates_without_dimension, :as => :rateable, :class_name => "Rate",
  :dependent => :destroy, :conditions => {:dimension => nil}
has_many :raters_without_dimension, :through => :rates_without_dimension,
  :source => :rater  

has_one :rate_average_without_dimension, :as => :cacheable,
  :class_name => "RatingCache", 
:dependent => :destroy, :conditions => {:dimension => nil}


dimensions.each do |dimension|        
  has_many "#{dimension}_rates", :dependent => :destroy, 
    :conditions => {:dimension => dimension.to_s}, 
    :class_name => "Rate", 
    :as => :rateable

  has_many "#{dimension}_raters", :through => "#{dimension}_rates",
    :source => :rater         

  has_one "#{dimension}_average", :as => :cacheable, :class_name => "RatingCache", 
    :dependent => :destroy, :conditions => {:dimension => dimension.to_s}
end   

It raises an error:

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

I tried to change the first line into:

has_many :rates_without_dimension, :as => :rateable, :class_name => "Rate", :dependent => :destroy,-> { where(:dimension => nil) }

But it also raised an error, can you point me to what is wrong with it?

like image 790
Wazery Avatar asked Jul 08 '14 00:07

Wazery


1 Answers

Same problem described here https://teamtreehouse.com/forum/unknown-key-conditions

As I see in examples, lambda with condition should does after association name, because hash without {} can be only as last argument.

Try

has_many :rates_without_dimension, -> { where(dimension: nil) }, as: :rateable, class_name: "Rate", dependent: :destroy

p.s. you can use http://apidock.com/rails/Object/with_options to make it looks nicer

like image 171
Pavel Evstigneev Avatar answered Oct 10 '22 18:10

Pavel Evstigneev