A question that I hope you can answer for a Q&A app. Still very new with Rails. It should be fairly simple but there is a small issue that I run into whenever I am trying to create a list of links to show up that point to a RESTful route from a loop.
Here’s the code for the controller:
users_controller.rb
def list
@user = User.find(params[:id])
@users = User.find(:all, :select => :name)
end
def quiz
@user = User.find(params[:id])
@users = User.find(:all, :select => :name)
end
Here’s the code for the view:
<% if current_user.admin? %>
<ul>
<%- @users.each do |link| %>
<li><%= link_to link.name, quiz_user_path(@user, @quiz) %></li>
<% end %>
</ul>
<% end %>
Here’s the code for the route:
resources :users do
get 'quiz', :on => :member
end
What I want to do is generate individual links based on the name of the users and then link to the quiz page for that specific user. I’m pretty sure that something needs to be changed for the code in my view. Right now, all I’m getting is a link that all points to the current user which in this case is user 4. (http://localhost:3000/users/4/quiz)
Thanks for any quick tips to solve this.
Currently you are using the same @user instance variable for each link. Instead you need to use the variable set in your loop. The code below should work as expected:
I also renamed the variable from
linktouser, for clarity, since your iterating through users not links.