我正在做我的第一个Rails项目,我有一个小问题。我很感激你的帮助。我想使用每个迭代器显示当前用户的所有未决朋友请求。我的控制器:
class FriendRequestsController < ApplicationController
before_action :set_friend_request, except: [:index, :new, :create]
def index
@incoming = FriendRequest.where(friend: current_user)
@outgoing = current_user.friend_requests
end
def new
@friend_request = FriendRequest.new
end
def create
friend = User.find(params[:friend_id])
@friend_request = current_user.friend_requests.new(friend: friend)
if @friend_request.save
redirect_back(fallback_location: root_path), status: :created, location: @friend_request
else
render json: @friend_request.errors, status: :unprocessable_entity
end
end
当我尝试像下面这样的代码时,它有点工作,条件语句正常工作,但我知道这是一种糟糕的方式,所以我想使用@incoming,因为它是定义的。
<% if FriendRequest.where(friend: current_user).present? %>
<% ?.each do |request| %>
<li><%= ? %></li>
<% end %>
<% else %>
You don't have any friend requests
<% end %>
但是当我尝试这样做时:
<% if @incoming.present? %>
条件语句不能正常工作,并且有'你没有任何朋友请求',即使当前用户有一个待处理的朋友请求。我还不完全明白RoR中所有的东西是如何工作的,所以如果你能解释一下,我会很感激的。
<% if (frs = FriendRequest.where(friend: current_user)).present? %>
<% frs.each do |fr| %>
<li><%= fr.name %></li>
<% end %>
<% else %>
You don't have any friend requests
<% end %>
让我们从为传入的朋友请求创建一个特定的关联开始。
class User < ActiveRecord::Base
# ...
has_many :incoming_friend_requests,
class_name: 'FriendRequest',
source: :friend
end
由于Rails不能从关联的名称中派生出合适的列,所以我们指定了class_name
。source
告诉Rails在FriendRequest上的关联是反向的。
当你开始考虑即时加载和性能时,这是非常重要的。
例如:
@user = User.joins(:friend_requests, :incoming_friend_requests)
.find(params[:id])
让我们使用新的关系:
def index
@incoming = current_user.incoming_friend_requests
@outgoing = current_user.friend_requests
end
使用.any?
测试作用域或集合中是否有任何项。.any?
是相当聪明的,因为它不会发出查询,如果关联已经加载。
<% if @incoming.any? %>
<ul>
<% @incoming.each do |fr| %>
<li><%= fr.name %></li>
<% end %>
</ul>
<% else %>
<p>You don't have any friend requests</p>
<% end %>