Reputation: 131
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?
Upvotes: 1
Views: 82
Reputation: 33
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.
Upvotes: 0
Reputation: 81
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
Upvotes: 0
Reputation: 30071
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).
Upvotes: 4