Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails如何以及在何处为模型属性定义getter和setter方法_Ruby On Rails - Fatal编程技术网

Ruby on rails rails如何以及在何处为模型属性定义getter和setter方法

Ruby on rails rails如何以及在何处为模型属性定义getter和setter方法,ruby-on-rails,Ruby On Rails,嗨,我是Rails的新手 我很想知道rails如何以及在何处为列名称定义getter/setter方法 假设在users表中有一个name列 User.find_by_name some name。rails如何在幕后解决它。您的问题是关于基于属性的访问器方法 例如,如果用户对象具有两个属性first_name和last_name,rails会将此类映射到模型用户 如果打开位于/app/models/User.rb中的用户模型 class User < ApplicationRecord

嗨,我是Rails的新手

我很想知道rails如何以及在何处为列名称定义getter/setter方法

假设在users表中有一个name列

User.find_by_name some name。rails如何在幕后解决它。

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

例如,如果用户对象具有两个属性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个链接中学习