Ruby on Rails Loop Help Needed - ruby-on-rails

I've been attempting to find a solution to this problem for about the last 12 hours and simply have to admit defeat and ask the question...
I am currently working on a project which involves added a start rating feature to a product.
the_number = number_with_precision(product.no_of_stars, :precision => 0) gives me the average star rating for the product. I can display the number (eg 4) on the index.html.erb page but cannot for the life of me get it to render a star jpg for for each number (instead of the number).
I am aware of the difference between <%= and <% etc however because this is my first post, I'm unable to copy and past the code I've used :-(
SO... the_number (for example) would give me 4, however the following loop construct within my index.html.erb file keeps throwing an error reading
undefined methodtimes for "4":ActiveSupport::SafeBuffer`
the_number.times do
img src="my-image.jpg" alt=""
end
I understand the snippet above is not wrapped in the correct tags, but as explained before, it will not allow me too. Please assume that the 1st and 3rd line are wrapped in ruby tags without the '=' and the image is wrapped in the relevant html img tag. You can also assume that the rating 'system' works correctly.
Any help would be greatly appreciated :-)
Thanks

the_number.to_i.times do
img src="my-image.jpg" alt=""
end

would <%= ... Integer(expression resulting in 4) %> work for you?
to this you can append times and continue with the loop
such as
Integer(the_number).times do
img src="my-image.jpg" alt=""
end

Try casting the_number to an integer:
the_number.to_i
Then you should be able to call times on it.

Related

Basic rails joins.. Result is a resource

I'm quite new to rails and making an app that lists albums.
Each album should be loaded with two or three preview tracks from that album.
All I want to do is get the preview_url from the previews table where the album_id is the same as the current album.
In mysql, I would use a left join:
SELECT preview_id FROM previews WHERE album_id = '{$sanitized_album_id}'...
I'm just not sure how to achieve this in ruby.
I can't find a single example that isn't obsessed with posts and comments, and it just isn't clear enough to click yet.
My album controller method looks like this:
def show
#previews = Preview.where(album_id: #album.id).order(track_number: :asc)
end
And my show.html.erb file should loop the results with this (simplified) code:
<% #previews.each do |preview| %>
<iframe src="<%= preview %>"></iframe>
<% end %>
Although I see no errors and the right number of previews are loading for each album, the resulting code is nonsense to me.
I expect the preview variable inside the do loop to be something like
https://website.com/previews/1984628754234
Instead, it looks more like this:
#<Preview:0x00007fcc08572c38>
I guess this is the database resource or something, but not the actual data I [think I] requested.
All the youtubes and whatnot didn't help me and I've only got a few hairs left...
Any one of you fantastic coders able to spare a moment to show me my stupid mistakes?
Thank you!
This will load all the attributes of Preview, it internally is performing a SELECT *.
#previews = Preview.where(album_id: #album.id)
if looping through #previews you would need to call preview.preview_id on each entry to get the value for that column.
In order to get a query like you showed - SELECT preview_id - you could use Preview.where(album_id: #album.id).select(:preview_id). You would still need to call .preview_id on each entry in the list, but it wouldn't load additional data.
If you want to make a query but you just want the plain array of preview_id values, you can use Preview.where(album_id: #album.id).pluck(:preview_id).
See:
select
pluck
That's a Preview instance. You probably want a field on Preview like:
<iframe src="<%= preview.preview_url %>"></iframe>
You can't just load in the model.

rails 3 is printing html tags to screen instead of rendering them

I'm using vhochstein's fork of active_scaffold, which runs quite nicely on rails 3, except for a few small bugs - http://github.com/vhochstein/active_scaffold.
In rails 2.3, the following code disables a link:
return "<a class='disabled'>#{text}</a>" unless authorized
But in Rails 3, it causes the escaped html tags to be printed out instead as in the following photo:
How can I make the content of this return statement render the way it should in rails 3?
The code above, is from the list_column_helpers.rb file in vendor/plugins/active_scaffold/helpers/
UPDATE:
Floatless fixed this by suggesting to add .html_safe to the code.
I have since found that the folowing change also needs to be made as there's more than one bit of code that is respondible for disabling action links in active_Scaffold:
In /plugins/active_scaffold/frontends/default/views/_list_actions.html.erb change:
<%= record.authorized_for?(:crud_type => etc etc etc -%>
By making it use "raw"
i.e.
<%= raw record.authorized_for?(:crud_type => etc etc etc -%>
Anyway, thanks to floatless and hopefully mr hochstein will be able to use this stuff.
Try this:
return "<a class='disabled'>#{text}</a>".html_safe unless authorized

visual_effect after replace_html not working in rjs

In learning ruby on rails I've created a blog site. When the user adds a post via AJAX, the following rjs gets called:
page.replace_html 'posts', :partial => #posts
page.visual_effect :Highlight, 'post_' + #post.id.to_s
However, the highlight isn't happening.. neither is any sort of effect even a hide.
Clues:
It works if I just do an insert_html
for just the new post (but I want
to update the whole list of posts
at this time)
If I hard code the id to the next id in the sequence, it doesn't work on the post, but it does work on the next post. { ex.. hardcode post_100... no highlight on submit 100, highlight 100 on submit 101 }
Alert shows that 'post_' + #post.id.to_s is what is expected ( post_100, etc )
Any ideas or debugging suggestions?
Thanks,
Orlando
Can you alert the innerHTML of the $("post_#{#post.id}") before the visual_effect.
Does firebug give you an error when it gets to the visual_effect?
Can you do something else, like an alert after the visual_effect line?
Have you got the required js files included?
It's not really an answer to the problem, but I have since done away with reliance on rjs. Instead I'm following the pattern outlined here
http://blog.solnic.eu/2007/10/30/why-javascript-helpers-in-rails-are-evil
And now all effects are working as expected. Note that I did get the effect working when comments were added using effectively the same code that should have been working here, so I'm fairly convinced there was just some sort of weird operator error going on.

Multiple Markers on Google Map (Fails to display over 10 markers) - Ruby on Rails Environment YM4R Plugin

I have the following issue. I have a google map (using YM4r + Geokit) within Ruby on Rails, anyhow, i basically have an array of markers which are populated in the following manner
#shops.each do
|sto|
markers << GMarker.new (....)
end
They are definitely being stored fine as under 10 markers they are displayed just fine. The problem arises when there are more than 10 markers on the same page,
Further code related to displaying if this may help:
#map.overlay_global_init(GMarkerGroup.new(true, markers), "sto_markers")
in the html.erb file:
<%= GMap.header %>
<%= javascript_include_tag("markerGroup") %>
<%= #map.to_html%>
<%= #map.div(:width => 700, :height => 500)%>
Only 10 markers are displayed on screen instead of the correct amount in the markers array.
Has anyone ever encountered this issue please? i'm really at a loss on how to overcome this please
Hmm, I have never used these plugins (I prefer to work directly with the API, much easier :)), so this is just random thinking.
Have you looked in the source of the rendered HTML? In there you should have a Javascript Object or Array with all your markers defined. If all of them do show up there, then it is easier to pinpoint if the problem is on the Javascript or the Rails side. (That is what <%= #map.to_html%> should do unless I'm completely off).
Update:
After some looking into the plugin, I can't really tell what the error can be, however since it do put out everything in clear Javascript in the file, it would probably help a lot if you can post the rendered HTML source. I believe that you will find the solution by looking there.

Correct coding convention for embedded code on web page templates

I had come experience with PHP a time ago and now I'm learning to use Ruby on Rails. But one simple question bothered me in both these languages, so I think I can cross-post it to both tags.
As you know, one of the concepts there is that one can embed PHP or Ruby code into web page template. Then these statements are executed and result of its execution is inserted in certain places of the page, marked with "brackets" <%= ... %>.
Or... wait. We program Ruby/PHP, but not HTML. Maybe we should treat template as Ruby/PHP code, into which sometimes HTML markup is inserted? So the process is treated like that HTML are inserted into ruby code into the "brackets" %> ... <%.
These are two different approaches:
HTML page is the primary entity, and it is affected by code execution; or
code is the primary entity, and it is executed, while HTML snippets are inserted in certain places.
This philosophy leads to different possibilities in coding conventions: result of code execution influences the page If we adhere the first insight, then the code would look like this:
<p>
<% (1..10).foreach do |i| %>
Iteration number <strong><%= i %></strong>. <br/>
<% end %>
</p>
But if we stick to the second alternative, the code would be formatted like this:
<%
%><p><%
(1..10).foreach do |i|
%>Iteration number <strong><%
%><%= i %><%
%></strong>. <br/><%
end
%>
How should the concept of templates be construed? What concepts do you, way more experienced Web developers, account for the coding convention?
If this is in your View layer (and it should be), then the HTML is the primary entity. It's the most pertinent part of that layer -- marking up your data to display in meaningful ways to the user.
Even aside from that, your second example is nearly unreadable. I see what you're doing, but it took me a minute to wrap my brain around it. I've also never, ever seen View-layer code like your second example (and I would make it one of my priorities to change it wherever I saw it if it was in a project I was working on).
To be more concise: you're putting the emphasis on the wrong thing. In my opinion, readability trumps just about everything else. The coding style that produces the most readable code is therefore the most superior (ceteris paribus and YMMV, of course).
Maybe you should look into Haml? I don't know if there's a php equivalent, but as far as Rails goes, it's somewhere in between the two schemes. It's not quite code centric. But when used right, all the raw html is prepared programatically.
In short everything is considered text to be directly outputted, unless prefixed with either a %, - or =. Which translate to html-tag, ruby code that doesn't output. Ruby code that does output. Haml then uses whitespacing to nest things properly, much like python does. Raw html outputs untouched but using % to specify a tag handles closing tags.
Sample:
#outer-div
- #items.each do |i|
%span.item
= i
%br
Outputs
<div id="outer-div">
<span class="item">
item
</span>
<br>
</div>
See the haml tutorial for more information.
To answer the central question. The bulk of any page is going to be HTML or raw text. We reduce the bulk of that text with includes and helpers, but it's still there. If there were a truly code centered approach my use of it would depend on the ratio of program logic to html. Personally I'd rather go with the html centered approach.
If you are interested in a code-oriented view, this is something you might try implementing as a pure Ruby DSL:
tag :p, :class => 'iterations-container' do
(1..10).each do |i|
text "Iteration number "
tag :strong { text i }
text "."
tag :br
end
end
Or perhaps instead of tag :p do ... end, you may favor tag.p do ... end.
I recommend doing only very simple logic in your template files. That way designers who can edit HTML can easily edit even those files to alter the layout if need be.

Resources