简体   繁体   English

Ruby / Rails实例变量不在对象中

[英]Ruby / Rails Instance Variables Not In Object

I've recently forayed into Ruby (on Rails), and now I'm stuck. 我最近涉足Ruby(在Rails上),但现在陷入困境。

I've created a class called Habit in habit.rb , shown below. 我在habit.rb创建了一个名为Habit的类,如下所示。

require 'date'

class Habit < ActiveRecord::Base
  attr_reader :created_at, :start
  attr_accessor :name, :record

  belongs_to :user

  after_initialize do
    @name = name
    @record = []
    @start = Date.today.yday()
    @created_at = Time.now()
  end
end

Steps to reproduce issue (in rails console --sandbox ): 重现问题的步骤(在rails console --sandbox ):

  1. star_monkey = Habit.create(name: "draw star")
  2. star_monkey

This returns #<Habit id: 1, name: nil, days: nil, start: nil, created_at: nil, updated_at: "2013-10-14 21:32:35"> . 这将返回#<Habit id: 1, name: nil, days: nil, start: nil, created_at: nil, updated_at: "2013-10-14 21:32:35">

However, when I explicitly request an instance variable, like @name , @record , or @start , the proper values are returned. 然而,当我明确地要求一个实例变量,像@name@record ,或@start ,返回正确的价值观。

star_monkey.name # returns "draw star"
star_monkey.record # returns []
star_monkey.start # returns 287

My question is: How is it that star_monkey.#{variable} is the correct value, but the record doesn't 'save' the proper value? 我的问题是: star_monkey.#{variable}是正确的值怎么star_monkey.#{variable} ,但是记录没有“保存”正确的值? And secondly, how would I remedy this? 其次,我该如何补救?

In the console you are using the create method which automatically saves the new object with the values provided to it. 在控制台中,您使用的是create方法,该方法会自动使用提供给它的值保存新对象。 If you use new , then it will not save the object. 如果使用new ,则它将不会保存该对象。 If you want to check, try to see the id of the object while using create and new method. 如果要检查,请在使用createnew方法时尝试查看对象的ID。 You will see the difference. 您将看到差异。 When you use create it will automatically get saved with id in it but when you use new it will not save unless you use object.save . 当使用create ,它将自动以id进行保存,但是当使用new ,除非使用object.save否则不会保存。 Thanks 谢谢

由于某种原因,使用下面的设置属性起作用。

self[:attribute] = "value"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM