Pergunta

Eu tenho uma classe de modelo simples:

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

Estou tentando definir o atributo content assim:

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)

Mas se eu fizer

sen[:content] = "Hello" - This updates the attribute
sen.write_attribute(:content,"Hello") - This updates the attribute

Estou confuso sobre o que está acontecendo aqui e por que, em alguns casos, minha atualização funciona, enquanto em outros não.Eu também tenho o mesmo problema com o atributo get.Sen.Content retorna nil, mas sen [: conteúdo] retorna o conteúdo correto que tenho outra classe de modelo e, neste caso, todos os quatro métodos mencionados acima para obter/definir atributos funcionam em todos os atributos

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

Alguém pode me ajudar e me dizer por que get/set funciona em certos casos, mas não em outros?Estou usando o Mongo (1.7.0) usando o mongóide (2.5.0) usando trilhos (3.2.8)

Foi útil?

Solução

Tente remover attr_accessor :content,:num_votes,:last_submitted.O attr_accessor O método é usado para criar métodos para simplesmente definir e ler uma variável de instância no objeto.Por exemplo, para attr_accessor :content, você acaba com os métodos:

def content= (something)
    @content = something
end

def content
    @content
end

A primeira não envolve save chamada para atualizar o banco de dados, apenas uma atualização da variável de instância na memória.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top