Get name from table has many , belong to relationship

Hi Guys

I have a table with


has many
belong to

Employee table

employee id addressid
12 12
13 13

i need to access addressid data from address table

please guide me

Hi Karthik,

Firstly I should say you should be more specific than that, the info is not very clear.

Secondly I will try to help you based on what I understand of your question.

Say you create a new employee this way :

@employee =[:employee])

You could do this in the controller create method :

@employee.address = Address.find() #find the address you want.

Now I will also advice you, in the new.html.erb form where your filling the Employee info, you could have a select drop down with Address data and depending on what you select, you would then automatically assign the address.



def new

@addresses = Address.all



<%= :address_id, @addresses.collect {|address| [address.text,]}

the above will generate the needed select drop down for selecting the address, the values would be the id whereas the text of the options would be address.text assuming that text field is the field of address which holds the address string.

Hope it helps.

Thanks & Regards,
Dhruva Sagar.

Stephen Leacock - “I detest life-insurance agents: they always argue that I shall some day die, which is not so.”

I'd argue for a person table (employees are people too), an address
table, and a full join table. A person can have many addresses, and an
address can have many people. People move, and you may want to keep
history on a person's past addresses (especially if there's a payroll or
tax implication).

id, first_name, last_name, etc, etc
has_many :residences
has_many :addresses, :through => :residences

id, line_1, line_2, city, state, postal_code, etc, etc
has_many :residences
has_many :people, :through => :residences

additional fields, perhaps start_date, end_date, and anything else that
might be related to an instance of this person at this address.
belongs_to :person
belongs_to :address

Maintenance of residences becomes a bit more involved (do you delete the
residence, or just end it - which gets to that residence history
question), but the flexibility might pay off later...

Showing field values is as simple as

@person.addresses.each do |address|


@address.people.each do |person|