如何在使用STI时强制转换ActiveRecord :: AssociationRelation?

时间:2015-08-23 18:13:39

标签: ruby-on-rails rails-activerecord

我正在努力施展'从一个关联到其STI子类的一组记录。

# Parent class
class Basket < AR::Base
  has_many :fruits
end

# Base STI class
class Fruit < AR::Base
  belongs_to :basket
  scope :coconuts, -> { where type: 'Coconut' }
end

# Child STIs classes
class Banana < Fruit
end

class Coconut < Fruit
end

目标是通过ActiveRecord::AssociationRelation范围获取CoconutFruit#coconuts个对象。问题是我的查询返回的关联总是由Fruit个对象组成。

Basket.first.fruits.coconuts.class.name
=> "ActiveRecord::AssociationRelation"

Basket.first.fruits.coconuts.arel.engine.name
=> "Fruit"

我缺少一个链接,以便将我的结果集转换为从Coconut类实例化的对象。

任何提示都表示赞赏。感谢

1 个答案:

答案 0 :(得分:0)

每个对象可以使用 if (mysqli_num_rows($result) > 0) { echo"<table class='table table-hover table-striped table-responsive'>"; while($row = mysqli_fetch_assoc($result)) { echo"<tr class='table_row'>"; echo"<td>" . $row['1'] . "</td>"; echo"<td>" . $row['2'] . "</td>"; echo"<td>" . $row['3'] . "</td>"; echo"<td>" . $row['4'] . "</td>"; echo"<td><a href='#'><button type='button' class='btn btn-danger btn-xs glyphicon glyphicon-remove-circle'></button></a></td>"; echo"</tr>"; } echo"</table>"; }

http://apidock.com/rails/ActiveRecord/Base/becomes