2010-06-20 122 views
0

UPDATE红宝石显示对象

我型我秀功能

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 

模型

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 

嗨,

我是一种新的以Ruby on Rails的。我想显示如下 -

- !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: {} 

我觉得我做错了

<% @data.Register.each do |c| %> 
    <tr> 
     <td><%=h c.Term.number %></td> 
     <td><%=h c.Course.course_name %></td> 
    </tr> 
    <% end %> 

感谢

回答

1

on Rails的Ruby的约定是,类资本,一个类的实例是不。

如果模型包括注册申报

has_one term 

然后你会使用

registration = Registration.find xxx # get an instance of the Registration model 
registration.term # access the associated term model 
        # do not use registration.Term 

所以访问术语...

1)你必须向我们展示你的控制器代码。和你的ActiveRecord类文件 - 你有没有正确定义使用belongs_to,has_many声明的关系?

2)你的SW应该更像:

# 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

此外,非常小心命名模式“会话” - 潜在的问题是,CGI会话可以存储成模型会话(如果启用了数据库支持的会话)。

+0

感谢您的回复,我添加了我的控制器方法和一些模型代码。 是的关系工作,我想我正在做我的发现错误。 – Alex 2010-06-20 17:57:20

+0

查看你的development.log,看看你的sql是否是你想要的。此外,应该可能是︰@contact = Contact.find(params [:id] .to_i) – 2010-06-20 20:56:22

+0

谢谢,我会玩弄它。 – Alex 2010-06-21 21:49:21