ActiveRecord的,由多态属性发现 [英] ActiveRecord, find by polymorphic attribute

查看:194
本文介绍了ActiveRecord的,由多态属性发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了这个:

 类事件<的ActiveRecord :: Base的
  belongs_to的:historizable,多态=>真正
结束

用户= User.create!
 

我可以:

  Event.create(:historizable =>用户)!
 

但我不能:

  Event.where(:historizable =>用户)
#Mysql2 ::错误:未知列'events.historizable'在'where子句
 

我要代替做到这一点:

  Event.where(:historizable_id => user.id,:historizable_type => user.class.name)
 

更新

code重现该问题:的https://gist.github .COM / fguillen / 4732177#文件polymorphic_where_test-RB

解决方案
  

本已在Rails的主实施,将在提供   导轨4.感谢。

- @carlosantoniodasilva

Having this:

class Event < ActiveRecord::Base
  belongs_to :historizable, :polymorphic => true
end

user = User.create!

I can:

Event.create!(:historizable => user)

But I can't:

Event.where(:historizable => user)
# Mysql2::Error: Unknown column 'events.historizable' in 'where clause'

I have to do this instead:

Event.where(:historizable_id => user.id, :historizable_type => user.class.name)

Update

Code that reproduces the issue: https://gist.github.com/fguillen/4732177#file-polymorphic_where_test-rb

解决方案

This has been implemented in Rails master and will be available in Rails 4. Thanks.

@carlosantoniodasilva

这篇关于ActiveRecord的,由多态属性发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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