![](/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.