Ruby Displaying objects
UPDATE
my show function
def show
@contact = Contact.find(params[:id])
@data = Register.all :include => {:session =>[:term, :course]} , :conditions => ["contact_id = ?", params[:id]]
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @contact }
end
end
Models
class Register < ActiveRecord::Base
belongs_to :session
belongs_to :contact
end
class Session < ActiveRecord::Base
belongs_to :term
belongs_to :course
has_many :registers
has_many :contacts, :through => :registers
end
Hi,
I am kind of new to ruby on rails. I want to display the following -
- !ruby/object:Register
attributes:
created_at: 2010-06-20 11:39:06
updated_at: 2010-06-20 11:39:06
session_id: "32"
contact_id: "601"
id: "1"
attributes_cache: {}
session: !ruby/object:Session
attributes:
created_at: 2010-06-19 10:16:13
term_id: "26"
updated_at: 2010-06-19 10:16:13
id: "32"
course_id: "4"
attributes_cache: {}
course: !ruby/object:Course
attributes:
created_at: 2010-05-30 14:36:24
updated_at: 2010-05-30 14:36:28
course_name: Beginner
id: "4"
course_type: Running
attributes_cache: {}
term: &id001 !ruby/object:Term
attributes:
number: "1"
start_date: "2010-06-19"
created_at: 2010-06-19 10:16:13
updated_at: 2010-06-19 10:16:13
id: "26"
attributes_cache: {}
I think I'm doing it wrong
<% @data.Register.each do |c| %>
<tr>
<td><%=h c.Term.number %><开发者_开发百科/td>
<td><%=h c.Course.course_name %></td>
</tr>
<% end %>
Thanks
The Ruby on Rails convention is that classes are capitalized, instances of a class are not.
If a model Registration includes a declaration
has_one term
Then you'd access the term by using
registration = Registration.find xxx # get an instance of the Registration model
registration.term # access the associated term model
# do not use registration.Term
So...
1) You need to show us your controller code. And your ActiveRecord class files--have you properly defined the relationships using belongs_to, has_many declarations?
2) Your sw should be more like:
# Controller
def show
# Shows all the registrations for person_id
# args: params['person_id']
@registrations = Register.find_all_by_person_id(params['person_id'].to_i_
end
# View
<% @registrations.each do |r| %>
<tr>
<td><%=h r.term.number %></td>
<td><%=h r.course.course_name %></td>
</tr>
<% end %>
ADDED
Also, be very careful about naming a model "session" -- the potential problem is that CGI sessions may be stored into the model Session if db-backed sessions are turned on.
精彩评论