簡體   English   中英

從Rabl模板訪問模型方法

[英]Access model method from rabl template

我正在嘗試在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

這是我的rabl模板文件-

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,但是不確定。

聽起來您似乎已經接近解決這個問題。 您可以使用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' } } 這是指向RABL中node的文檔鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM