在其他编程语言中,我可以通过在逻辑运算符中分解条件来分隔条件,但在ruby中(我使用的是rails)似乎不是。是代码还是语法?:
<% if (current_user && current_user.id == @user.id)
|| @user.profile_privacy === 0
|| (@user.profile_privacy === 1
&& current_user
&& current_user.user_friendships.find_by_friend_id(@user.id)
&& current_user.user_friendships.find_by_friend_id(@user.id).state == true ) %>
答案 0 :(得分:3)
您的视图中不应该包含所有逻辑,但要修复代码,请将操作符移到行尾:
<% if (current_user && current_user.id == @user.id) ||
@user.profile_privacy === 0 ||
(@user.profile_privacy === 1 &&
current_user &&
current_user.user_friendships.find_by_friend_id(@user.id) &&
current_user.user_friendships.find_by_friend_id(@user.id).state == true )
%>
答案 1 :(得分:2)
您应该尝试尽可能多地保留模板中的逻辑。
例如,您可以将一些逻辑移到User
模型中:
class User < ActiveRecord::Base
def has_user_as_friend user
user_friendships.find_by_friend_id(user).state == true
end
def is_private
profile_privacy === 0
end
end
你可以将其中的一部分移动到你的控制器中:
def show
@user = User.find(params[:id])
@is_current_user = current_user.id == @user.id
end
然后,你的病情会变得有点简单:
<% if (@is_current_user || @user.is_private) %>
我没有完全复制您的条件,但希望这可以为您提供一些关于如何简化if
声明的想法。