我正在使用 Rails 4.0.0, gem 'mongoid', '~> 4', :github=>"mongoid/mongoid", Ruby 2.0.0p247
我有以下型号:
class Policy
include Mongoid::Document
field :policy_number, type: String
field :user_id, type: Integer
belongs_to :user
embeds_many :employees
end
class Employee
include Mongoid::Document
field :first_name, type: String
field :last_name, type: String
embedded_in :policy
embeds_one :partner
end
class Partner
include Mongoid::Document
field :first_name, type: String
field :last_name, type: String
embedded_in :employees#, :inverse_of => :partner
end
在我的控制器中:
def show
@user = User.find(current_user.id)
@policy = @user.policies.first
在我的政策/show.html.erb
<% @policy.employees.each do |emp| %>
<%= emp.first_name %>
<%= emp.partner.first_name %>
<% end %>
在 MongoDB 中:
/* 0 */
{
"_id" : ObjectId("52763eb6612d48113c000000"),
"employees" : [
{
"_id" : ObjectId("5276574e612d4815ca000000"),
"dob" : null,
"first_name" : "Jon",
"last_name" : "Jonson",
"partner" : {
"_id" : ObjectId("527737ca612d487238050000"),
"first_name" : "Bob",
"last_name" : "Bobbit",
},
}
],
"policy_number" : "RF087-2423525",
"user_id" : ObjectId("52761fce612d487b2c000000")
}
emp.first_name 按预期显示,但 emp.partner.first_name 错误,未定义方法 `first_name' for nil:NilClass