Rails best practice for checking if an object exists before displaying an attribute in a layout

I have the following code in the layout:

Posted <%=time_ago_in_words post.created_at %> ago 
<% if post.has_tag != nil %>
   in the <%= post.get_first_tag.name %> category
<% end %>

And the following code in the post model that inherits the form ActiveRecord :: Base

def has_tag
 !self.tags.empty?   
end

def get_first_tag
 self.tags[0]   
end 

Tags are also inherited from ActiveRecord :: Base and Post 'has_many' Tags

First: This is the best way to check if a mail object has at least one associated tag attribute.

Second: Should I put this logic in a helper method?

Third: Why the following job does not work (it returns # where the tags should be):

in the <%= post.tags.to_sentence %> category, 

I assume that its tags are not actually stored as an attribute of the array, but I really don't know.


+3
source share
2 answers

, . , self.tags.empty? true false, post.has_tag nil.

, , true false . , post.has_tag? (, empty? ).

, , ; , .

, # , , , .

post.tags.map(&:name).to_sentence

.

+4

-, , ,

<% if post.has_tag %>

<% if post.has_tag != nil %>

has_tag nil, , , "..." .

, : , , .

+1

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


All Articles