Show last message in a message array

╄→гoц情女王★ 提交于 2019-12-24 01:44:57

问题


Regarding my last attempted answer, I could achieve what I wanted. Once the app is working I noticed something is different: only the person that created the message and sends a message was only showing. If I reply, I do not see the reply and I know the problem.

My Message model has tables: [:id, :user_id, :to, :body, ...]

:user_id would be similar to from as that is used to determine who created the message.

User 1 would be Client and User 2 is Student. Student sends a message to Client. Only my client side the code is as this:

#Controller Index:

@messages = Message.where(to: current_user.id) # My replies are not included here
       .order(user_id: :asc, created_at: :desc)
       .select('distinct on (user_id) *')

I'm saying give me all messages that's addressed to me (:to) an id of 1.

I won't see my reply because of the :to column.

My (client) reply looks like this:

to: #student id
user_id: #client id

And student message:

to: #client id
user_id: #student id

So because the to now point to an id, let's say 2 I wont see the reply. I may need to change up the model but if you see an easy way, please let me know.

Edit:

Answer that works great:

@messages = Message.where(to: current_user.id).or(Message.where(user_id: current_user.id))
                 .order(connection: :desc, created_at: :desc)
                 .select('distinct on (connection) *')

回答1:


Since you are using Rails 5, you can take advantage of it's or method:

Message.where(to: current_user.id).or(
 Message.where(user_id: current_user.id)
).order(connection: :desc, created_at: :desc)
 .select('distinct on (connection) *')


来源:https://stackoverflow.com/questions/37879169/show-last-message-in-a-message-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!