Rails 关联中的未知键 [英] Unknown key in Rails association

查看:58
本文介绍了Rails 关联中的未知键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下关联代码:

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   

它引发了一个错误:

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

我试着把第一行改成:

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?

推荐答案

此处描述的相同问题 https://teamtreehouse.com/forum/unknown-key-conditions

正如我在示例中看到的,带条件的 lambda 应该在关联名称之后执行,因为没有 {} 的哈希只能作为最后一个参数.

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

试试

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

附言你可以使用 http://apidock.com/rails/Object/with_options 让它看起来更好

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

这篇关于Rails 关联中的未知键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆