0

根据“子节点”下的 RABL 文档,以下是可能的:

object @user
child :posts do |user|
  attribute :title unless user.suspended?
end

这意味着user块产生的变量是父对象@user

但是,当我尝试以下操作时:

collection @listings
child :address do |listing|
  attribute :number_and_street unless listing.address_hidden?
end

我得到一个NoMethodError

undefined method `address_hidden?' for #<Address:0x007fb83d6eaf80>

这意味着该块正在产生子地址对象而不是父@listing对象,正如文档所暗示的那样。

我能看到的唯一解决方法是类似address.listing.address_hidden?,这会导致数据库查询过多,所以我想避免这种情况。

难道我做错了什么?有没有办法解决这种行为?

4

1 回答 1

0

当您使用集合时,子块不会产生单个对象。我要做的是将它分成两个文件。

index.json.rabl

collection @listing
extends "app/view/listings/base"

base.json.rabl

object @listing
child :address do |listing|
  attribute :number_and_street unless listing.address_hidden?
end

编辑:我刚刚注意到您正在使用 rabl-rails gem。我的解决方案适用于“rabl”,我不太确定这个宝石:)

于 2013-07-31T03:01:38.843 回答