【问题标题】:has_one :conditions being interpreted as attributes?has_one :条件被解释为属性?
【发布时间】:2011-08-29 20:32:11
【问题描述】:

这个协会:

class Business < ActiveRecord::Base
  has_one    :map_address, :as=>:addressable, :class_name => 'Address', :conditions => {'addresses.map_address'=>true}, :dependent => :destroy
end

导致此错误:

ruby-1.8.7-p334 :005 > n = Business.new
ruby-1.8.7-p334 :006 > n.build_map_address
ActiveRecord::UnknownAttributeError: unknown attribute: addresses.map_address

用来读取的代码

:conditions => {:map_address=>true}

但缺少表名会导致查找时出现此问题(它将字段名放在错误的表上):

ActiveRecord::StatementInvalid (PGError: ERROR:  column counties.map_address does not exist
                                                             ^
SELECT "businesses".* FROM "businesses"   INNER JOIN "addresses" ON ("businesses"."id" = "addresses"."addressable_id" AND "addresses"."addressable_type" = 'Business')  INNER JOIN "counties" ON ("counties"."id" = "addresses"."county_id") AND counties."map_address" IS NULL  WHERE (counties.id = 23)  ORDER BY businesses.updated_at DESC):

这个选项:

"adresses.map_address is true"

在查找时产生此错误:

PGError: ERROR:  missing FROM-clause entry for table "adresses"
LINE 1: ..." ON ("states"."id" = "addresses"."state_id") AND adresses.m...
                                                             ^
: SELECT "businesses".* FROM "businesses"   INNER JOIN "addresses" ON ("businesses"."id" = "addresses"."addressable_id" AND "addresses"."addressable_type" = 'Business')  INNER JOIN "states" ON ("states"."id" = "addresses"."state_id") AND adresses.map_address is NULL  WHERE (states.id = 4)  ORDER BY businesses.updated_at DESC

所以我的问题是为什么 rails 会试图将这种情况转化为属性?我怎样才能让它双向工作?我的猜测是 rails 正在尝试将条件设置为新记录的默认值。

【问题讨论】:

  • 好吧,没关系,我发现对表名的误解实际上来自searchlogic,所以这毕竟不是rails问题。 :(
  • 那么正确的代码是什么样的?

标签: ruby-on-rails activerecord model model-associations


【解决方案1】:

为什么不

has_one    :map_address, :as=>:addressable, :class_name => 'Address', :conditions => {:map_address => true}, :dependent => :destroy

【讨论】:

  • 原来是这样,见问题
【解决方案2】:

map_attribute 是一个字段吗?在这种情况下会出现错误,因为您有addresses.map_address,但是您在谈论什么地址对象?通过写地址你不是指一个特定的地址
换句话说,Map_address 似乎是一个对象的属性,所以 object1 有它的 map_address,object2 有它的 map_address,但是当你输入地址时,你不是指任何对象,并导致错误。

【讨论】:

  • 4.3.2.4 :conditions :conditions 选项允许您指定关联对象必须满足的条件(在 SQL WHERE 子句使用的语法中)。所以在这种情况下,addresses 是一个表名
  • 确认 {:addresses => {:map_address => true}} 也不起作用
猜你喜欢
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
相关资源
最近更新 更多