2012-12-30 26 views
0

我想换我的头周围Rails和已经进入一些困难,试图理解为什么有些事情的工作和别人不一样的Rails显示的HAS_ONE关系表

例如,具有2个表:

类用户

table users 
email:string 
password:string 

类资料

table profiles 
firstname:string 
lastname:string 
city:string 
user_id:integer 

现在è ach用户应该有1个配置文件。

user.rb我

has_one :profile 

和profile.rb模块所以在

belongs_to :user 
现在

所有我想要做的是显示了在表两张表

<table> 
<tr> 
    <th>User_ID</th> 
    <th>Email</th> 
    <th>Password digest</th> 
    <th>First Name</th> 
    <th>Last Name</th> 
    <th>City</th> 
</tr> 

<% @users.each do |user| %> 
<tr> 
    <td><%= user.id %></td> 
    <td><%= user.email %></td> 
    <td><%= user.password %></td> 
    <td><%= user.profile.firstname %></td>%></td> 
    <td><%= user.profile.lastname %></td>%></td> 
    <td><%= user.profile.city %></td>%></td> 
</tr> 
<% end %> 
</table> 

我有一个控制器显示索引页

def index 
#this works 
@users = User.all(:include => :profile) 
end 

这段代码我找到了工作,它正确显示表。

但是我有一个其他代码的列表,我通过试图让它起作用来收集/拼凑出来,这是行不通的。

所以码的该列表会一直DEF内部索引单独特林两个表

连接
  1. @users = @ users.build_profile() 抛出错误:未定义的方法`build_profile”的零:NilClass

  2. @users = @ users.profile 抛出错误:零未定义的方法`轮廓”:NilClass

  3. @users = @ user.collect {|用户| user.profile} 抛出错误:未定义的方法`收集 '的零:NilClass

  4. @users = Profile.find(:所有) 抛出错误:未定义的方法`电子邮件' 的#Profile:0x46da5a0

    <% @users.each do |user| %> 
    <tr> 
    <td><%= user.id %></td> 
    <td><%= user.email %></td> 
    <td><%= user.password %></td> 
    <td><%= user.proflie.firstname %></td> 
    
  5. @users = @ profile.create_user() 抛出错误:未定义的方法`create_user”的零:NilClass

  6. @users = @ users.profiles 抛出错误:未定义的方法`型材的零: NilClass

  7. @users = @ user.each {| user |用户。型材} 抛出错误:每个”的零未定义的方法`:NilClass

为什么所有这些其他的失败,他们似乎对于有类似的问题(连接两个表1到其他用户的工作零关系)

回答

0

大多数遇到刚才的事实,你在nil调用方法所引起的问题。您需要初始化@users集合,然后才能调用方法。还要确保你实际上在数据库中有一些用户。

获取所有用户:

@users = User.all(:include => :profile) 
@users = User.includes(:profile) # I prefer this syntax 

建立一个配置文件。请注意,您需要调用这个在一个特定的User,而不是由all方法给出的集合:

@profile = @users.first.build_profile # This won't actually save the profile 

获取第一用户的个人资料

@profile = @users.first.profile 

获取所有配置:

@profiles = @users.collect { |user| user.profile } 

获取第一用户的电子邮件:

@email = @users.first.profile.email 

其余的只是上面的一个稍微修改过的版本。