Has_Many:通过或:finder_sql
我已经确定了我想要的东西,但我似乎无法以导轨设计师所寻找的方式获得它。 基本上,我有(请留出多元化/等问题):
人际关系(父母,后代)
我正在努力让所有后代成为一个单亲,以及许多后代的单亲(假设每个后代只有一个父母)。
我可以在模型中以下列方式执行此操作:
has_one :parent, :through => :relationships, :foreign_key => :human_id, :source => :source_human has_many :offsprings, :finder_sql => 'SELECT DISTINCT offsprings.* ' + 'FROM humans offsprings INNER JOIN relationships r on ' + 'r.human_id = offsprings.id where r.source_human_id = #{id}'
我必须这样做,因为更好的方法:
has_many :offsprings, :through => :relationships, :foreign_key => :source_human_id, :source => :human
是不可能的,因为在has_many中忽略了外键(根据这里的文档: http : //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many )
但是,现在我收到此错误:
DEPRECATION WARNING:不推荐使用基于字符串的关联条件插值。 请改用proc。 因此,例如,has_many:older_friends,:conditions =>’age>#{age}’应更改为has_many:older_friends,:conditions => proc {“age>#{age}”}。 (从(irb)的irb_binding调用:1)
但是,无论我如何破解:条件在这里,它似乎没有:finder_sql想要参与。 有什么想法吗?
如果你这样做会怎么样
has_many :offsprings, :finder_sql => proc { "SELECT DISTINCT offsprings.* " + "FROM humans offsprings INNER JOIN relationships r on " + "r.human_id = offsprings.id where r.source_human_id = #{id}" }
实际上,我是这样写的:
has_many :offsprings, :finder_sql => proc {OFFSPRING_SQL % {id: id}} OFFSPRING_SQL = "SELECT DISTINCT offsprings.* FROM humans offsprings INNER JOIN relationships r ON r.human_id = offsprings_id WHERE r.source_human_id = %{id}"
我认为它使关联更容易理解,它使裸SQL更容易编辑。 它还利用了基于字符串的参数插值。
- ActiveRecord has_many:通过在批量分配上复制计数器缓存
- has_one:through => multiple
- Rails:ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:找不到源关联
- 如何使用has_many:through和honor:conditions创建新记录?
- Rails:has_many有额外的细节吗?
- 使ActiveRecord连接模型属性在查询结果中可用
- HMT collection_singular_ids =删除连接模型是直接的,不会触发销毁回调
- 源reflection宏无效:has_many:through
- has_many的问题:通过,缓存,触摸和counter_cache