Note: We are using this
if
statement within aform_for
or aform_with
, Rails Form builders.
- While working on one of my project, I needed to show a link to edit or delete a resource or objects only if they belong to the user that created that object. So I Know about if statement and unless method, But I do not need to render and else part of the statement, just the if.
<% if tag.user == current_user %>
<%= link_to 'Edit', edit_tag_path(tag), method: :get %>
<%= link_to 'Delete', tag_path(tag), method: :delete, data: { confirm: 'Are you sure?' } %> <br>
<% end %>
This is not even a do block, this block of code will only run if the condition set inside the if
is true
- So basically if the user that created the tag is equal to the
current_user
currently log in them, it will render this links into the view.
Another shorter way to do this would be just passing an if
at the end of the link_to
block.
<%= link_to 'Edit', edit_tag_path(tag), method: :get, if tag.user == current_user %>
# This link_to would only render if the IF Statement is true else It would not Render.
Note: Ruby would read the view or any file from the top to bottom. This mean that if something evaluate to false like this it would be skipped and not rendered and the next action or block after this one would run.
- NOTE: This is one of 30 blogs that I would be attempting to write over the next 30 days to improve my writing skills.
Top comments (0)