我正在尝试围绕 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 索引中单独连接两个表
@users = @users.build_profile() 抛出错误:nil:NilClass 的未定义方法 `build_profile'
@users = @users.profile 引发错误:nil:NilClass 的未定义方法 `profile'
@users = @user.collect { |用户| user.profile } 抛出错误:nil:NilClass 的未定义方法 `collect'
@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>
@users = @profile.create_user() 抛出错误:nil:NilClass 的未定义方法“create_user”
@users = @users.profiles 引发错误:nil:NilClass 的未定义方法“profiles”
@users = @user.each { |用户| user.profiles } 抛出错误:nil:NilClass 的未定义方法 `each'
为什么所有这些其他的都失败了,它们似乎适用于有类似问题的其他用户(以 1 到零的关系连接两个表)