![](/img/trans.png)
[英]Accessing current user information with Janrain and Ruby on Rails
[英]Ruby on Rails - accessing nested attributes of current user
我正在嘗試訪問部分Rails中的嵌套屬性; 讓我解釋一下我的問題:
我根據我在另一個問題中提到的dana mulder的教程編寫了一個簡單的消息服務。 user
has_many conversations
,而conversation
has_many messages
。 每個對話都有一個收件人和一個發件人,每個消息都有一個布爾型read
,默認情況下將其設置為false
。
我要做的是編寫一個簡單的函數,該函數遍歷用戶所參與的對話中的每條消息,檢查用戶在對話中收到的最后一條消息是否讀為== true,而不是自己發送給在我的應用程序導航中的“消息”鏈接旁邊顯示一個小旋鈕。
我基本上要檢查的是(多行以提高可讀性):
<%= if current_user.conversations.all.messages.last.user_id != current_user.id && current_user.conversations.all.messages.last.read == false %>
Message link with bubble beside it
<% else %>
Message link
<% end %>
此語法不起作用..如何遍歷用戶所涉及的每個會話,檢查每個會話的最后一條消息(如果此用戶寫的消息,如果不是已讀的消息)?
雖然像Conversation.last.messages.last.content
這樣的東西正在工作,但current_user.conversations.all.messages.last.content
卻沒有..我發現它有點困擾Rails模型的可訪問性。
提前致謝! 我希望我對我的解釋足夠好。
最好的祝福
您要如何處理current_user.conversations.all.messages.last.content
? 因為conversations.all
是關聯,所以它不是對話,因此messages
不是可用的方法。 Conversation.last
是一種對話,因此您可以在其上調用messages
。
您可以嘗試使用current_user.conversations.last.messages.last.content
來獲取上次對話的最后一條消息,也可以在User上使用“ has_many:through”關系
class User ...
has_many :conversations
has_many :messages, through: :conversations
end
這樣,如果您希望所有用戶的消息和current_user.messages.last
都獲得最后一條消息(即使它不是來自上一次對話),則可以執行current_user.messages
。
我建議您閱讀有關關聯的Rails指南https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
編輯:要知道用戶是否有未讀消息,可以使用has_many :through
關聯並執行類似的操作
current_user.messages.where(read: false).where.not(user_id: current_user.id).any?
這將返回true
則不會讀取用戶對話中ID為!= current_user.id的任何消息。 否則為false
。
您可以使用count
代替any?
如果您不想知道未讀郵件的實際數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.