Noah Clark
Noah Clark

Reputation: 8131

Pass Variable between Views in 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.

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 %>

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

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

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

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.

Upvotes: 3

Views: 5378

Answers (2)

Elmatou
Elmatou

Reputation: 1384

If users have one or many relationships, it could be smarter to user nested routes.

then you will be able to create relationship for a specific user through a direct url.

eg : new_user_relationship_path(user) # => /user/2134/relationship/new

then in your relationship controller a params[:user_id] would evaluate to 2134

you should look at : http://guides.rubyonrails.org/routing.html

Upvotes: 3

Thilo
Thilo

Reputation: 17735

This

link_to 'Connect', new_relationship_path, :id => user.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)

Upvotes: 6

Related Questions