0

我正在尝试围绕 Rails 进行思考,并且在试图理解为什么某些东西有效而其他东西无效时遇到了一些困难

例如,有 2 个表:

类用户

table users
email:string
password:string

班级简介

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

现在每个用户应该有 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>

我有一个带有索引页的控制器 Show

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

我发现的这段代码有效,它可以正确显示表格。

但是我有一个其他代码列表,这些代码是我通过尝试使其工作而收集/拼凑的,但这些代码不起作用。

因此,此代码列表将在 def 索引中单独连接两个表

  1. @users = @users.build_profile() 抛出错误:nil:NilClass 的未定义方法 `build_profile'

  2. @users = @users.profile 引发错误:nil:NilClass 的未定义方法 `profile'

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

  4. @users = Profile.find(:all) 抛出错误:#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() 抛出错误:nil:NilClass 的未定义方法“create_user”

  6. @users = @users.profiles 引发错误:nil:NilClass 的未定义方法“profiles”

  7. @users = @user.each { |用户| user.profiles } 抛出错误:nil:NilClass 的未定义方法 `each'

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

4

1 回答 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

其余的只是上述内容的略微修改版本。

于 2012-12-30T16:12:52.887 回答