What's the cleanest way to add a class attribute to an html element in a view in rails
-
20-08-2019 - |
Question
I'm writing some Rails code for a partial view, and I want it to only show a comment field if somebody is already logged onto a site here.
If the page is viewed by someone who isn't a member of the site yet, the shared/comment_not_logged_in
fragment should be passed in.
However, I'm totally stumped as to why I can't run the same check to decide if the page should add the class attribute "missing_your_voice" to the enclosing div element here:
<li class="user_submission_form bubble comment_form <% "missing_your_voice" if not current_user %>">
<% if current_user %>
<%= image_tag(current_user.avatar(:comment), :class => "profile_pic") %>
<% form_for [parent, Comment.new] do |f| %>
<%= render "comments/form", :f => f %>
<% end %>
<% else %>
<%= render :partial => 'shared/comment_not_logged_in' %>
<% end %>
</li>
The same idiom, "missing_your_voice" if not current_user
returns the string in irb, and also in the console debugger.
What am I doing wrong here?
Solution
You forgot an =
. Replace <%
by <%=
, so that you get:
<%= "missing_your_voice" if not current_user %>
Remember that <% ... %>
will only run Ruby code, but not display anything. Using <%= ... %>
will run the code and display the result of the expression.
OTHER TIPS
As molf already pointed out, there's a missing = on your view.
It should be <%=
.
Other than that, be sure to make your controller method available to your view by calling helper_method in your controller.
Take a look on the documentation if needed.