问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/24621827/unknown-key-in-rails-association