Rails在显示之前检查对象存在的方式

Sha*_*fun 5 ruby-on-rails ruby-on-rails-3

我想找到一个很好的方法来检查我的对象,然后我在视图中显示它们,所以我不会得到错误.

这是我的控制者

 @user = User.find_by_username(params[:username])
 @profile = @user.profile 
 @questions = @user.questions
Run Code Online (Sandbox Code Playgroud)

这是我的观点

 <% unless @profile.blank? %><%= link_to 'Edit Profile', :controller => 'profiles', :action => 'edit' %><% end %>


     <% unless @user.blank? %>
        Username:<%= @user.username %><br />
    Member Since:<%= @user.created_at.strftime("%d %B %Y")  %><br />
    <% end %>

  <% unless @profile.blank? %>
    First Name: <%= @profile.first_name %><br />
    Last Name: <%= @profile.last_name %><br /><br />
    About: <%= @profile.body %><br /><br />
    Location: <%= @profile.location %><br />
    Birthday: <%= @profile.birthday.strftime("%d %B %Y") %><br />
    <% end %>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我正在使用不止一种检查(检查除非@ profile.blank?),我认为会有更好的方法来做到这一点.

是否有任何Rails方式可以做出比我想出的更聪明的事情?

jib*_*iel 10

<%= if @object.present? %>
Run Code Online (Sandbox Code Playgroud)

看起来比我简单得多

<%= unless @object.blank? %>
Run Code Online (Sandbox Code Playgroud)

特别是当我们有多个条件语句(&&\ ||\ and\ or)时.

api.rubyonrails.org


sam*_*207 6

正如我所见,你无法跳过这个@ .blank?验证,因为你不想显示记录,如果它们是空的,但我没有什么建议

1 - 将以下部分作为部分

<% unless @user.blank? %>
    Username:<%= @user.username %><br />
    Member Since:<%= @user.created_at.strftime("%d %B %Y")  %><br />
<% end %>
Run Code Online (Sandbox Code Playgroud)

<% unless @profile.blank? %>
  First Name: <%= @profile.first_name %><br />
  Last Name: <%= @profile.last_name %><br /><br />
  About: <%= @profile.body %><br /><br />
  Location: <%= @profile.location %><br />
  Birthday: <%= @profile.birthday.strftime("%d %B %Y") %><br />
<% end %>
Run Code Online (Sandbox Code Playgroud)

它可以让您的视图更清晰,并且可以让您灵活地在应用中的任何软件中使用它们

2 - 走下面的一行

<% unless @profile.blank? %><%= link_to 'Edit Profile', :controller => 'profiles', :action=> 'edit' %><% end %>
Run Code Online (Sandbox Code Playgroud)

在配置文件显示内部更合适

干杯

sameera