相关疑难解决方法(0)

attr_accessor和attr_accessible之间的区别

在Rails中,attr_accessor和之间有什么区别attr_accessible?根据我的理解,using attr_accessor用于为该变量创建getter和setter方法,以便我们可以像Object.variable或那样访问变量Object.variable = some_value.

我读到这attr_accessible使得该特定变量可供外界使用.有人可以告诉我这是什么区别

ruby ruby-on-rails

235
推荐指数
4
解决办法
12万
查看次数

实例变量:self vs @

这是一些代码:

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end
Run Code Online (Sandbox Code Playgroud)

我想知道的是两者的区别@age,并self.ageage_difference_with方法.

ruby instance-variables self

175
推荐指数
4
解决办法
4万
查看次数

直接访问实例变量与使用访问器方法

谁能解释通过self.attribute和通过访问实例属性之间的区别@attribute

ruby accessor instance-variables

80
推荐指数
1
解决办法
1万
查看次数

Rails - before_save不工作?

我正在关注Michael Hartl的RoR教程,它涵盖了密码加密的基础知识.这是目前的用户模型:

class User < ActiveRecord::Base
    attr_accessor :password

    attr_accessible :name, :email,: password, :password_confirmation

    email_regex = /^[A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/
                                              #tests for valid email addresses.

    validates :name, :presence => true,
                     :length => {:maximum => 50}
    validates :email, :presence => true,
                      :format => {:with => email_regex},
                      :uniqueness => {:case_sensitive => false}
    validates :password, :presence => true,
                         :length => {:maximum => 20, :minimum => 6},
                         :confirmation => true

    before_save :encrypt_password

    private

        def encrypt_password
            @encrypted_password = encrypt(password)
        end

        def encrypt(string)
            string
        end
end
Run Code Online (Sandbox Code Playgroud)

(显然这不是在进行任何加密,因为加密方法并没有真正实现,但这不是我的问题)

然后我编写了以下规范(根据教程):

require 'spec_helper' …
Run Code Online (Sandbox Code Playgroud)

ruby callback ruby-on-rails-3

8
推荐指数
1
解决办法
1万
查看次数