轨道如何以及在何处定义模型属性的 getter 和 setter 方法



嗨,我是 Rails 的新手,

我渴望知道 rails 如何以及在何处定义列名称的 getter/setter 方法

假设我在用户表中有一个名称列

User.find_by_name "some name".轨道如何在幕后解决它。

您的问题是关于基于属性的访问器方法

例如,如果您有具有 2 个属性 first_name 和 last_name 的用户对象,则 Rails 会将此类映射到模型用户。

如果您打开用户模型位于/app/models/User.rb 中

class User < ApplicationRecord
# if you see line above meaning this class
# inherit from ApplicationRecord
# and there are many methods inside parent class
# instance level methods and class level methods
...
end
@user = User.new
# create new instance
@user.changed?
@user.first_name = 'John'
@user.changed_attributes
# these 2 methods (changed? and changed_attributes) inherit from ApplicationRecord
# class methods
User.find_by_first_name('John')
# beside instance methods rails also inherit class level methods if you use model name User (not instance name @user)

引用:

  • 我想建议您从下面的2个链接中学习

  • https://guides.rubyonrails.org/active_model_basics.html

  • https://guides.rubyonrails.org/active_model_basics.html#attribute-based-accessor-methods

最新更新