Unknown key in Rails association

自闭症网瘾萝莉.ら 提交于 2019-12-05 21:03:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!