i have a loop that, when it comes to a certain name will skip that record and display everything else:
<% @records.each do |record| %>
<% if record.task.project.project_name == "SKIP"%>
<% else %>
Do some stuff like display...
<% end %>
<% end %>
If the loop doesnt come across any records with a project name "skip" then i need to hide something using jquery. If the loop comes across 1 or more "skip"'s then i need to show something using jquery. i have the javascript function ive written:
function show() {
if (<%= @count %> > 1)
{
$(".toil").show();
}
else
{
$(".toil").hide();
}
}
where @count
is a variable in ruby intialized at 0. and incremented everytime the projectname is skip. i tried to do this with code soemthing like this:
<% @records.e开发者_如何学运维ach do |record| %>
<% if record.task.project.project_name == "SKIP"%>
<%= javascript_tag do -%>
<% @count = @count + 1%>
<% end -%>
<% else %>
i know this doesnt work but id like to know how i would do this and if theres a better, more "Ruby-Way".
Two options that I see:
- Don't use jquery at all. Set a class on the element you want to show/hide based on @count directly in your view. Then use CSS to hide/show that element. If there's no reason to ever show the element if @count=0 then just don't render it at all.
- Set a javascript variable in your view (not a ruby variable). Something like
<script>var count = <%= @count %>;</script>
and then use that in your js.
Keep the @count
variable in Rails and generate a different content for the show()
function, depending on the value of @count
:
<%= javascript_tag do -%>
function show() {
<% if @count > 1 %>
$(".toil").show();
<% else %>
$(".toil").hide();
<% end %>
}
<% end -%>
This way you do not need to 'transport' the @count
variable to jQuery as you handle both situations on the server directly, keeping it nice and simple.
Edit: It seems that the javascript_tag
in your example is used wrong, for more information/examples on the javascript_tag
take a look at APIDock.
精彩评论