Rails Link_to with Loop - RESTful 路由 [英] Rails Link_to with Loop - RESTful routes

查看:37
本文介绍了Rails Link_to with Loop - RESTful 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望您能在问答应用中回答一个问题.Rails 还是很新的.它应该相当简单,但是每当我尝试创建链接列表以显示指向循环中的 RESTful 路由的点时,都会遇到一个小问题.

这是控制器的代码:

users_controller.rb

def 列表@user = User.find(params[:id])@users = User.find(:all, :select =>:name)结尾测验@user = User.find(params[:id])@users = User.find(:all, :select =>:name)结尾

这是视图的代码:

<% if current_user.admin?%><ul><%- @users.each 做 |link|%><li><%= link_to link.name, quiz_user_path(@user, @quiz) %></li><%结束%><%结束%>

这是路线的代码:

资源:用户做得到'测验',:on =>:成员结尾

我想要做的是根据用户的姓名生成单独的链接,然后链接到该特定用户的测验页面.在我看来,我很确定需要为代码更改某些内容.现在,我得到的只是一个指向当前用户的链接,在这种情况下是用户 4. (http://localhost:3000/users/4/quiz)

感谢您提供解决此问题的任何快速提示.

解决方案

目前,您对每个链接使用相同的 @user 实例变量.相反,您需要使用循环中设置的变量.下面的代码应该按预期工作:

<% if current_user.admin?%><ul><%- @users.each 做 |user|%><li><%= link_to user.name, quiz_user_path(user) %></li><%结束%><%结束%>

为了清楚起见,我还将变量从 link 重命名为 user,因为您遍历的是用户而不是链接.

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:

<% if current_user.admin? %>
  <ul>
    <%- @users.each do |user| %>
      <li><%= link_to user.name, quiz_user_path(user) %></li>
    <% end %>
  </ul>
<% end %>

I also renamed the variable from link to user, for clarity, since your iterating through users not links.

这篇关于Rails Link_to with Loop - RESTful 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆