I have a list of items in a table, where each item displays an attribute of a Ruby class called Record. Each item sits in its own row. Each <tr>
has an id
that mirrors the name of the attribute, and at any given time one row will have the class alpha
and one will have the class beta
— as shown below:
Initial code
<table>
<tr id="attribute_1">
<td><%= @record.attribute_1 %></td>
</tr>
<tr id="attribute_2" class="alpha">
<td><%= @record.attribute_2 %></td>
</tr>
<tr id="attribute_3">
<td><%= @record.attribute_3 %></td>
</tr>
<tr id="attribute_4" class="beta">
<td><%= @record.attribute_4 %></td>
</tr>
</table>
The rows labeled alpha
and beta
are changing constantly. I want to be able to determine the id of the table row with these respective classes and pass them to ruby, so that I can (for the purposes of this question) switch them, for example (and yes, I know there are way easier ways to do this without using ruby at all, but just go with it).
The way I'm trying to do this right now utilizes jQuery, which calls a function when a button is pressed.
$(function document() {
$(".button").click(function() {
var alphaId = $(".alpha").attr("id");
var betaId = $(".beta").attr("id");
$(".alpha td").html("<%= @record." + betaId + " %>");
$(".beta td").html("<%= @record." + alphaId + " %>");
});
});
This doesn't work because the ruby fails to compile. Ulti开发者_运维技巧mately, the result should look like this:
Intended Results
<table>
<tr id="attribute_1">
<td><%= @record.attribute_1 %></td>
</tr>
<tr id="attribute_2" class="alpha">
<td><%= @record.attribute_4 %></td>
</tr>
<tr id="attribute_3">
<td><%= @record.attribute_3 %></td>
</tr>
<tr id="attribute_4" class="beta">
<td><%= @record.attribute_2 %></td>
</tr>
</table>
Notice the outputs of attribute_2 and attribute_4 are switched. Let me know if you have any alternative approaches to solving this problem! Thanks.
Edit
Also, it's worth noting that the jQuery sits in the view file views/records/switch.js.erb and is executed server-side. For example, the following code works fine:
$(function document() {
$(".button").click(function() {
var alphaId = $(".alpha").attr("id");
var betaId = $(".beta").attr("id");
$(".alpha td").html("<%= @record.attribute_4 %>");
$(".beta td").html("<%= @record.attribute_2 %>");
});
});
and I would go for this, but the number of attributes is enormous and they're constantly changing.
Of course it fails to execute:
ruby is executed server side
your js would only be executed client-side
=> they can't work together this way.
You should create a js variable and work with it in you js. Something like:
var records = <%= @record.to_json%>;
And then depending on the json structure:
$(".alpha td").html(records[betaId]);
精彩评论