Accessing another table in a different rhtml file


#1

Hi Everybody,

I am trying to access the elements of a different table within another
tables layout file. Here is basically what I am trying to do:

<% if table1.ITEM_ID == table2.ID %>

<%=h table1.ITEM_ID %>
<% end %>

But it gives me an error for table2. Here is the error I get:
“undefined local variable or method”

I’m very new to RoR and would appreciate any help.

Thanks,
Roshini


#2

Hi
I’m new to rails too.
but have you assign value to table2 in your controller? (@table2 =
something).

burlight


#3

Well for now, I have it in a for loop that goes through the entire
table2 db to match and see if the same ID exists in both tables. But,
everytime I make any reference to table2 even in the for loop, it
throws the same error "“undefined local variable or method”


#4

Okay…but how would I access the @cars in the UserController?


#5

you have to poulate the @cars variable in the UserController, just
like you did with @users:

def UserController < ApplicationController

def list

    @cars = Car.list
    @users = User.list

end

end

simple as that. the above is only pseudo code obviously, as you did
not give any code example what you do in your controller to find your
desired dataset.


#6

Hi, you should be able to easily retrieve values from other tables.
For example, if you have have the following:

Example models:

class User < ActiveRecord::Base

def self.list

   User.find( :all )

end

end

class Car < ActiveRecord::Base

def self.list

     Car.find( :all )

end

end

Example controllers:

def CarController < ApplicationController

def list

    @cars = Car.list

end

end

class UserController < ApplicationController

def list

   @users = User.list

end

end

Now. in your views, you can easily reference both the @users and @cars
instance variables within your views. Please remember that each model
represents an OO view of the underlying table (i.e. cars and users
tables). Again, this is just an example and you can customize it to
do whatever you like. For example, you might want to get a subset of
the available users or retrieve a user by an attribute. If this is
the case, then you can easily define the appropriate method(s) within
the controller and/or the model to achieve this goal. Well, I hope
that this helps and I wish you the best of luck.

-Conrad