得到了一個超級快速的問題。我還是新來的鐵軌,並嘗試遵循這兩個問題,但他們不適合我:Why does Array.to_s return brackets?和ruby 1.9 how to convert array to string without brackets。從欄杆採集字符串顯示n
我想顯示最後的消息和它在我的聊天室應用程序中發出的日期。我能夠使用此代碼獲得結果,但它有括號,並且我希望刪除這些括號。這裏的任何幫助都會很棒,我也附上了截圖。非常感謝!
Show.html.erb
For the Date: <%= chatroom.messages.last(1).pluck(:created_at) %> For the Last Message in Chatroom: <%= chatroom.messages.last(1).pluck(:body) %>
DirectMessages控制器
class DirectMessagesController < ApplicationController
before_action :authenticate_user!
def show
users = [current_user, User.find(params[:id])]
@messageduser = User.find(params[:id])
@chatroom = Chatroom.direct_message_for_users(users)
@chatroomall = current_user.chatrooms
@messages = @chatroom.messages.order(created_at: :desc).limit(100).reverse
@messagelast = @chatroom.messages.last(1)
last_message = @chatroom.messages.last
render "chatrooms/show"
end
private
def chatroomuserlocator
@chatroomlocator = Chatroom.find(params[:chatroom_id])
end
end
感謝@Dan的響應和上下文,我試着做了這樣的錯誤消息「undefined method' created_at'for nil :NilClass「 – Omar
使用」.try「的最後一個工作!感謝億丹! – Omar
沒問題。我很高興它有幫助。我只是在這裏更新我的評論,因爲我有一個錯字。如果你想從消息數組中刪除'nil'元素,你可以使用[compact](https://apidock.com/ruby/v1_9_3_392/Array/compact)這樣的方法:'<%= chatroom.messages。 'compact.last.created_at%>'。如果返回錯誤,您的chatroom實例中可能沒有任何消息。如果你只是想避免返回一個錯誤,你可以使用[try](https://apidock.com/rails/v3.2.1/Object/try)這樣的方法:'<%= chatroom.messages.last。嘗試(:created_at)%>' –