从rabl模板访问模型方法

时间:2018-02-18 16:14:13

标签: ruby-on-rails ruby rabl

我正在尝试在Ruby on Rails rabl模板中访问模型方法,但是我无法弄清楚如何将参数传递给函数。这是模型代码 -

class Conversation < ActiveRecord::Base
    has_many :messages, dependent: :destroy
    belongs_to :sender, foreign_key: :sender_id, class_name: User
    belongs_to :recipient, foreign_key: :recipient_id, class_name: User

  def opposed_user(user)
    user == recipient ? sender : recipient
  end

end

这是我的兔子模板文件 -

collection @conversations, object_root: false
attributes :id, :sender_id, :recipient_id

node :otheruser do |c|
    c.opposed_user(current_user)
end

具体来说,我试图返回的是opposed_user,但我上面提到的错误是wrong number of arguments (0 for 1)current_user正在返回正确的用户,所以这是简单的事情还是我以错误的方式解决它?

更新

如果我使用c.opposed_user(current_user).to_json它会工作但是json返回一个转义字符串而不是实际的json对象。我想也许我需要使用child而不是node但不确定。

1 个答案:

答案 0 :(得分:1)

听起来你很接近解决这个问题。您可以使用as_json代替to_json来修复您已有的RABL模板。

最终模板如下所示:

collection @conversations, object_root: false
attributes :id, :sender_id, :recipient_id

node :otheruser do |c|
  c.opposed_user(current_user).as_json
end

使用RABL,有许多不同的处理方法。当您使用node时,如果您提供字符串,则只需添加一个密钥。由于to_json会返回一个字符串,因此最终会显示{ otheruser: "whatever string you provided" }

但是,如果您使用as_json,则最终会提供node也可以处理的哈希值。例如,像这样:

node :otheruser do |c|
  { id: 1, name: 'Bob' }
end

您最终会得到如下所示的JSON:{ otheruser: { id: 1, name: 'Bob' } }。这是一个link to the documentation on node in RABL

相关问题