如果用户有'消息'
,我正试图展示一些内容视图/消息/ index.html.erb
<% if @user.messages.any? %>
You have messages!
<% else %>
Sorry, you have no messages
<% end %>
控制器/ messages_controller.rb
class MessagesController < ApplicationController
def index
@user = current_user
@messages = @user.messages
end
当我实现此代码时,即使用户没有消息(由rails console确认:
user = User.find(1)
user.messages.any?
=> false
消息'你有消息!'仍然出现
还要考虑添加身份验证使用设计 gem
答案 0 :(得分:1)
<% if @user.messages.any? %>
<%= "User with id #{@user.id} has messages" %>
<% else %>
<%= "User with id #{@user.id} doesnt have messages" %>
<% end %>
这将显示类似的东西
User with id 5 has messages
要么
User with id 6 doesnt have messages
现在从rails控制台验证这个
User.find(5).messages.any?
答案 1 :(得分:0)
尝试
<% if @user.present? %>
<%= puts "User is selected" %>
<% if @user.messages.present? %>
<%= puts "User have message" %>
<% end %>
<% end %>