Mongoid 不保存设定值

Mongoid doesn't save set value

我的问题是,对于未自动设置的属性,我总是收到 nil 值。以下是一些示例:

2.3.1 :001 > t = Team.new(name: "team_1", code: "a123")
 => #<Team _id: 581b2f230640fd0cf4070a47, created_at: nil, updated_at: nil, code: nil, name: nil> 
2.3.1 :002 > t.save
 => true 
2.3.1 :003 > t
 => #<Team _id: 581b2f230640fd0cf4070a47, created_at: 2016-11-03 12:35:58 UTC, updated_at: 2016-11-03 12:35:58 UTC, code: nil, name: nil> 
2.3.1 :004 > t.name = "team_1"
 => "team_1" 
2.3.1 :005 > t
 => #<Team _id: 581b2f230640fd0cf4070a47, created_at: 2016-11-03 12:35:58 UTC, updated_at: 2016-11-03 12:35:58 UTC, code: nil, name: nil>

这是我在示例中使用的模型:

class Team
  include Mongoid::Document
  include Mongoid::Timestamps

  attr_accessor :name, :code, :owner_id, :learnin_object_ids, :active

  field :code, type: String
  field :name, type: String
end

我的 Gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'

gem 'mongoid', '~> 6.0'
gem 'bson_ext'
gem 'moped'
gem 'devise',  '~> 4.0'

group :development, :test do
  gem 'byebug', platform: :mri
  gem 'rspec-rails', '~> 3.0'
  gem 'factory_girl_rails', '~> 4.0'
  gem 'database_cleaner', '~> 1.0'
end

group :development do
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

如何保存正确的数据?

问题是由 attr_accessor 引起的。删除后,将保存正确的数据。