単純なモデルクラスがあります。
class Sentence
include Mongoid::Document
include Mongoid::Timestamps
field :content, :type => String
field :num_votes, :type => Integer
field :last_submitted, :type => Time
field :meaning_id , :type => String
belongs_to :word
belongs_to :user
attr_accessible :content,:num_votes,:last_submitted
attr_accessor :content,:num_votes,:last_submitted
end
私は次のようにコンテンツ属性を設定しようとしています:
sen = Sentence.first
sen.content = "Hello" - This does not update the attribute(no error thrown)
sen.write_attributes(content: "hello") - This does not update the attribute(no error thrown)
しかし、私がそうするなら
sen[:content] = "Hello" - This updates the attribute
sen.write_attribute(:content,"Hello") - This updates the attribute
ここで何が起こっているのか、そしてある場合には私のアップデートが機能するのに、他の場合には機能しないのはなぜかについて私は混乱しています。get属性についても同じ問題があります。sen.contentはnilを返しますが、sen [:content]は正しいコンテンツを返します。別のモデルクラスがあります。この場合、属性を取得/設定するための上記の4つのメソッドはすべてすべての属性で機能します。
class User
include Mongoid::Document
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
## Database authenticatable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
validates_presence_of :email
validates_presence_of :encrypted_password
## Recoverable
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
## Rememberable
field :remember_created_at, :type => Time
## Trackable
field :sign_in_count, :type => Integer, :default => 0
field :current_sign_in_at, :type => Time
field :last_sign_in_at, :type => Time
field :current_sign_in_ip, :type => String
field :last_sign_in_ip, :type => String
## Confirmable
# field :confirmation_token, :type => String
# field :confirmed_at, :type => Time
# field :confirmation_sent_at, :type => Time
# field :unconfirmed_email, :type => String # Only if using reconfirmable
## Lockable
# field :failed_attempts, :type => Integer, :default => 0 # Only if lock strategy is :failed_attempts
# field :unlock_token, :type => String # Only if unlock strategy is :email or :both
# field :locked_at, :type => Time
## Token authenticatable
# field :authentication_token, :type => String
include Mongoid::Timestamps
field :name, type: String
validates :name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
index({ email: 1 }, { unique: true, name: "email_index" })
field :rank, type: String
field :num_words, type: Integer
field :time_in_city, type: Time
field :last_logged_in, type: Time
field :points, type: Integer
has_many :sentences
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
end
誰かが私を助けて、get / setが特定の場合には機能するが、他の場合には機能しない理由を教えてもらえますか?私はmongo(1.7.0)を使用していますmongoid(2.5.0)を使用していますレールを使用しています(3.2.8)