Asarluhi Asarluhi - 2 months ago 6
HTML Question

How to use a data model attribute as html id attribute

I have a User model with

name
and
email
attributes.
I would like to use a user's name as html id attribute for a table row.
Requiring
id
a string and being
name
a string, I am undecided whether the following notation is correct:

<tr id=<%= user.name %>>


or am I expected to explicitly use double quotation marks after the html id attribute, so for instance use instead one of the following solutions:

<tr id="<%= user.name %>">
<tr id="#{<%= user.name %>}">


I am pretty sure that
<tr id="<%= user.name %>">
would produce
id="'Dave'"
, instead of
id="Dave"
(quotation inside quotation), while I am not sure that the interpolation makes any sense at all. The second solution would work if I chose
user.id
instead of
user.name
.

Answer
<tr id="<%= user.name %>">

is the correct construction. It is better to use the record id as has already been suggested but, hey, it's your code. You will need to make sure that the name field doesn't contain spaces or other characters not allowed in id attributes.

In my Rails apps, I prefix all my id attributes as follows to ensure that they are absolutely unique on any page:

<tr id="user_<%= user.id %>">
Comments