Rails : Using local variable for an image path - ruby-on-rails

I have a simple cms, and basically I have a detailed view of sauces which has an image.
In the database table I have the pictures' URL stored.
When I want to display the image, and put the variable where the image_tag url should go, the program throws an error. How do I do this?
<tr>
<th>Picture</th>
<td><%= image_tag("sauces/sauces_piri.png") %></td>
</tr>
thats the URL put in manually which works. The EXACT same string is stored in the database in a field called pic_url.
I already have a variable which stores the sauce object. How do I put the sauce field, instead of the direct URL.
I have tried
<tr>
<th>Picture</th>
<td><%= image_tag("#{sauce.pic_url}") %></td>
</tr>
This does not work

I basically resolved the issue. The problem was that the sauces is an instance variable not a standard variable.
Because I was not using the # sign before the sauce it was not recognising the variable.
So the correct code is as follows :
<td><%= image_tag("#{#sauce.pic_url}") %></td>
Hope this helps

Related

How to present JSON information in a html.erb file (Ruby)?

I am new to Ruby/Rails and I've been given a task to make a Ruby site (.html.erb) look a bit nicer. One of the things requested was to present information on the site, which is currently shown as JSON, as nice-looking html. The line of html.erb is as follows:
<%= #buyer.generate_profile.inspect %><br>
and will display the information it receives on the site as JSON. What can I do to parse through the JSON and make it so that the site will display the information as proper html?
You might want to check out JSON.pretty_generate. You could display the result in a code block like:
<%# If your data is a JSON string, convert it to a hash %>
<% hash = JSON.parse(#buyer.generate_profile) %>
<pre>
<code>
<%= JSON.pretty_generate(hash) %>
</code>
</pre>
So the generate_profile method returns a Hash object and calling inspect on it will create string output of the Hash syntax in Ruby, so the result looks like your comment.
If you wanted it to look like JSON, the simplest way would be to use the to_json method like this
<%= #buyer.generate_profile.to_json %>
but honestly, it's not much better. And even if you were to look into methods that can present it with proper line breaks, etc. that wouldn't improve it much either imo.
I would recommend you learn how to iterate over the keys and values in a Hash, because that would allow you to create a custom HTML layout that could look however you wanted it to.
As an example, I'll show you how you could create a simple table based on the data from your comment
<table>
<thead>
<tr>
<th>Key</th>
<th>XX</th>
<th>YY</th>
<th>ZZ</th>
</tr>
</thead>
<tbody>
<% #buyer.generate_profile.each_pair do |key, sub_hash| %>
<tr>
<td><%= key %></td>
<td><%= sub_hash[:xx] %></td>
<td><%= sub_hash[:yy] %></td>
<td><%= sub_hash[:zz] %></td>
</tr>
<% end %>
</tbody>
</table>
The main thing here is the use of each_pair which is a method that iterates over each key and value of the hash. In your case it sounds like the values of the first hash are sub-hashes, hence my use of sub_hash as the block argument.
You could technically use each_pair on the sub-hashes as well, but I'm guessing they all have the same keys, that's why I manually added columns and cells for XX, YY, ZZ in combination with sub_hash[:xx], etc.
Once you get a hang of how iterating over Hashes and arrays work, then I would recommend scrapping the table design and instead look into more modern web design approaches like Flex and CSS-Grid, but one thing at a time :)

Can someone explain to me what this code is doing?

I am currently building an online course and I was having trouble accessing a lesson that is associated with a certain course.
A developer friend of mine solved the problem for me but I'm not really sure why this code works and if there are different ways, more of a Rails conventional way to write this code.
<% #courses.each do |course| %>
<tr>
<td><%= link_to course.title, "courses/#{course.id}" %></td>
</tr>
<% end %>
I am not sure what this part "courses/#{course.id}" is doing. Is there a way to write this using a more conventional seeming names route helper?
It should be the same as course_path(course)
This call just figure out the path for you. The expression in your code simply build this path putting together "courses/" and the id of the course (but using interpolation, not concatenation).
As Ursus answer explains, courses/#{course.id} creates URL directing to specific course path by using string interpolation. For example, if #courses variable is an array with Course objects with ids: [1, 2, 3], then you will receive links directing to "course/1", "course/2", course/3".
To replace that interpolation, you can simply write
<%= link_to course.title, course %>
It will create the same output as "courses/#{course.id}"
To learn more about string intepolation, you can start here: http://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html
For some reason your friend did this:
<td><%= link_to course.title, "courses/#{course.id}" %></td>
...instead of this:
<td><%= link_to course.title, course %></td>
...and I have no idea why. The second example is how you use links in Rails. The first example doesn't safeguard you against possible future URL changes.

Using Heroku, Rails sort is incorrect on updated_at timestamp column

I have a Rails 4.0 APP using PostgreSQL on Heroku. I am trying to display a table that is my XLog or transaction log, showing the last five entries in reverse order by updated_at timestamp. This works correctly on my local system. When I push it to Heroku, it sorts incorrectly.
I have checked the Heroku database definitions and the column is correctly listed as a timestamp. I have cloned the Heroku code back to my machine and verified that it is the same as what I pushed. At this point, I don't know why it doesn't work on Heroku when it works locally. And advice would be appreciated.
FWIW, the remote database and local database do not have the same data.
The code is: (Last line of log_sort was added to act as a breakpoint that would still pass the correct result.)
def self.last_objects object, count
logs = XLog.where(object: object).last(count)
log_sort = logs.sort_by{|log| log.updated_at}.reverse
log_sort
end
During execution to the breakpoint, you can see the variables passed:
This is the local result with the correct sort:
This is the Heroku result with the incorrect sort:
This is the Heroku PostgreSQL table definition for updated_at:
EDIT: View:
<% xlog = xlog_last(car.stock_number, 5) %>
...
<% xlog.each do |log| %>
<tr>
<td><%= log.associate %></td>
<td><%= log.proxy %></td>
<td><%= log.action %></td>
<td><%= log.status %></td>
<td><%= log.message %></td>
<td><%= log.value %></td>
<td><%= log.updated_at %></td>
</tr>
<% end %>
Helper:
def xlog_last(object, count)
XLog.last_objects object, count
end
EDIT:
I modified the sort_by to use an order method as follows. The results did not change at all. The same sorting error occurred and the exact same data was displayed in the exact same way:
New code:
def self.last_objects object, count
logs = XLog.where(object: object).order(updated_at: :desc).first(count)
end
I believe you need to use order to influence the actual sql query. Right now you are using sort_by which is sorting the data after you read in from the database. The order in the db is based on how it was inserted and could be different from heroku and your local system. When you export from heroku, and then import it, the ordering of the tables probably changes too.
A gem was incorrectly sorting the view. Correcting that issue fixed the problem. Still unsure why it didn't show in test except possibly for the data differences.

Weird rails pluralization issue

I have a ruby on rails application that recently started giving me issues.
I believe there may be a weird bug/feature in the way rails is pluralizing model names for the database.
For example,
I have a model called DiagExerciceWeekFive. The table in the database is called diag_exercice_week_fives. The pluralization works correctly here.
I think there may be a problem in the way rails is attempting to "de-pluralize" the table into the respective objects.
When I try to load up a simple form that displays all of my diagweekfives, I get this error:
uninitialized constant Diag::DiagExerciceWeekFife
Not once have I used that name in my application.
Here's the relevant bit of code that is throwing the error:
<% ExerciceWeekFive.all.each do |exercice| %>
<tr class="success">
<td><%= check_box_tag :exercices_week_five_ids, exercice.id, #diag.exercices_week_fives.include?(exercice), :name => 'diag[exercices_week_five_ids][]' %></td>
<td><%= exercice.number %></td>
<td><%= exercice.description %></td>
</tr>
The exception is thrown on the first <td> within the <tr>
Has anyone run into this before? I know little about rails, but I am trying to maintain some legacy code.
Thanks.

Undefined Method, across classes, for a database derived field

I'm aware that variants of this question have been asked before, but I do believe my question is different ;-)
I have 2 Ruby on Rails classes (with assoc. controllers, models, etc). These are Devices and Messages.
In the Devices index.html view, I need to make reference to the newest Message record.
<table>
<tr>
<th>Device Name</th>
<th>Checked</th>
</tr>
<% newestMessage = Message.find(:all, :order => "updated_at DESC", :limit => 1) %>
<% #devices.each do |device| %>
<tr>
<td><%= device.name %></td>
<td><%= newestMessage.updated_at %></td>
</tr>
<% end %>
</table>
(I believe I should move the logic to a helper, but for the time being I'm keeping it as simple as possible while I get it working)
When I access this blahblah.com/devices, I get...
undefined method `updated_at' for #<Array:0x103f36c00>
Due to the line,
<td><%= newestMessage.updated_at %></td>
Now, I've seen questions like this that suggest to add the equivalent of the following to messages_controller.rb,
attr_accessor :updated_at
However, I've tried this and it doesn't help. Also, I don't think this should be necessary anyway as 'updated_at' is derived from the database, built with scaffold, etc.
If I just print 'newestMessage' it seems to have a sensible value.
My question is, how should I access fields within newestMessage, which are of class Message from the Device index.html.erb?
Thanks in advance.
Try newestMessage = Message.last then newestMessage.updated_at

Resources