Allows you to check the existence of an object before displaying

I want to find a good way to check my objects before displaying them in a view so that I don't get errors.

This is my controller

 @user = User.find_by_username(params[:username])
 @profile = @user.profile 
 @questions = @user.questions

and this is my opinion

 <% 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 %>

As you can see, I use several checks of each type (check if not @ profile.blank?), And I think that there will be a better way to do this.

Is there a way for Rails to do something smarter than the one I came across?

+3
source share
4 answers

As I see, you canโ€™t miss this @blank? if you do not want to display entries if they are empty, but I have few suggestions

1 - Make the following sections as partial

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

and

<% 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 %>

.

2 -

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

sameera

+5

<%= if @object.present? %>

,

<%= unless @object.blank? %>

, (&&\||\and\or).

api.rubyonrails.org

+9

? , ActiveRecord::RecordNotFound, , , 404 .

P.S. .

0

According to the rail documentation, you can see if there are any related objects using the .nil association? Method:

if @book.author.nil?
  @msg = "No author found for this book"
end
0
source

Source: https://habr.com/ru/post/1766569/


All Articles