在 Rails 中的视图之间传递变量 [英] Pass Variable between Views in Rails

查看:35
本文介绍了在 Rails 中的视图之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚如何在两个视图之间传递一个变量,而且我已经查看了有关堆栈溢出的所有示例,但似乎无法使其正常工作.

I've been trying to figure out how to pass a variable between two views and I've looked at all the examples on stack overflow and I can't seem to make it work.

我的用户中有这个 -> index.html.erb

I have this in my users -> index.html.erb

<% @users.each do |user| %>
  <tr>
  <td><%= user.name %></td>
  <td><%= user.email %></td>
  <td><%= user.id %></td>
  <td><%= link_to 'Profile', user %></td>
  <td><%= link_to 'Connect', new_relationship_path, :id => user.id %><td>
  </tr>
<% end %>

我正在尝试将 user.id 传递给我的关系 -> new.html.erb 视图.

I'm trying to pass user.id to my relationships -> new.html.erb view.

在我的控制器中,我有:

in my controller I have:

class RelationshipsController < ApplicationController
    def new
        @id = params[:id]
    end
end

最后我有了关系 -> new.html.erb

and finially I have relationships -> new.html.erb

<section id="main">
  <h1>Sign Up</h1>
  <td><%= @id %></td>
</section>

我相信 :id 没有被正确传递.我从所有其他示例中遗漏了什么?我没有收到任何错误,只是没有显示任何内容.

I believe :id isn't being passed correctly. What am I missing from all the other examples? I get no errors, just nothing is displayed.

推荐答案

这个

link_to 'Connect', new_relationship_path, :id => user.id

将 :id 作为 html_option 传递给 link_to,因此它将用作链接元素上的id"属性.你想要的是将它作为参数传递给路由助手:

is passing the :id as an html_option to link_to, so it will be used as an "id" attribute on your link element. What you want instead is to pass it as a parameter to the route helper:

link_to 'Connect', new_relationship_path(:id => user.id)

这篇关于在 Rails 中的视图之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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