A while back, I had some doubts on the use of associations. I still haven't got a satisfactory guidance so that I can spring ahead with the project. I am trying to understand from a ruby point of view on doing things. Basically I have a controller that gives me a list of students. And each student may have say home address and mailing address. Hence I can model as shown below. How do I get the list of addresses other than using the for loop inside the another controller that should display addresses belong to the selected student along with the associated other information about the student? If I need to display the home address in the top of the rhtml page and say mailing address in the bottom of the page with other information in the middle, if we put a for loop inside the rhtml, it might look like a spaghetti code that I am not in very favour. class Student < ActiveRecord::Base has_many :addresses ... end class Address < ActiveRecord::Base belongs_to :student ... end Some time back when I asked this question, Joshua was very kind enough to follow this pattern. Unfortunately even after reading the api's I still haven't got it registered!! @student = Student.find(params[:id]) @addrs = @student.addresses @address = @addrs.build(params[:address]) # and so on... I am sure that this is very trivial for the folks in this forum. Please help me out... Thanks Silvy Mathews Check out the docs on ActiveRecord associations, specifically has_many. http://api.rubyonrails.org/classes/ActiveRecord/As... s.html
on 2006-01-26 02:52
on 2006-01-26 10:06
Silvy@funmail.com wrote: > page with other information in the middle, if we put a for loop inside > the rhtml, it might look like a spaghetti code that I am not in very > favour. The addresses will just come back as an array, so you could do something like: @addresses = @student.addresses @home_address = @addresses.first # or @addresses.shift @mailing_address = @addresses.last # or @addresses.pop Then you can refer to @home_address and @mailing_address wherever you like, without messing things up. Apologies if I've oversimplified...