Reputation: 23
On my Rails app, users can create their names and choose sex. On their profile page, both of their name and sex are already shown correctly. Next, I would like to change the color of their name depend on their sex instead of showing both name and sex, but it doesn't work well so far. I would appreciate if anyone teach it to me.
<%= form_tag("/users/#{@user.id}/update", {multipart: true}) do %>
<table>
<p>User name</p>
<input name="name" value="<%= @user.name %>">
<p>Sex</p>
<select name="sex" value="<%= @user.sex %>" selected><%= @user.sex %>>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" value="Submit">
</table>
<% end %>
<div class="user">
<div class="username"><%= @user.name %></div>
<div class="sex"><%= "(" + @user.sex + ")" %></div>
</div>
I edited Users/show.html.erb like this, but it doesn't work.
<div class="username">
<%= @user.name %>
<% if @user.sex == "Male" %>
<% @user.name color: blue; %>
<% elsif @user.sex == "Female" %>
<% @user.name color: red; %>
<% else %>
<% @user.name color: black; %>
<% end %>
</div>
I will add more code if it needs to be refered. Thank you very much.
ruby 2.6.4p104 / RubyGems 3.0.3 / Rails 5.2.3
Upvotes: 1
Views: 164
Reputation: 1333
You can set the sex info directly as classname
.
<style>
.username span{
color: black;
}
.username span.Male{
color: blue;
}
.username span.Female{
color: red;
}
</style>
<div class="username">
<span class="<%= @user.sex %>"><%= @user.name %></span>
</div>
Upvotes: 1
Reputation: 2086
One of the easiest way to do this is to use helper method:
<div class="username #{username_color(@user.sex)}">
<%= @user.name %>
</div>
in helpers, user_helper.rb
def username_color(sex)
case sex
when "Male" then "blue"
when "Female" then "red"
else "black"
end
end
and remember to tweak up your css styles
Upvotes: 1