#app/models/patient.rb
class Patient < ActiveRecord::Base
protected
def name=(value)
mod_name = []
value.split.each do |n|
n.split("")
type = n[0] ? "up" : "down"
n.send("#{type}case")
mod_name.push(n)
end
@name = mod_name.join
end
end
#app/controllers/patients_controller.rb
class PatientsController < ApplicationController
def create
@patient = Patient.new patient_params
@patient.save ? redirect_to(patients_path) : render(:new)
end
private
def patient_params
params.require(:patient).permit(:name)
end
end
你正在做的是试图覆盖setter 方法,这可以使用上面的代码来完成。更高效且不碍事。
我创建了以下方法
既然你是新人,让我解释一下。
请务必注意在哪里您正在使用此方法。
您当前已将其放入 模型,这意味着您必须调用它来操作使用该模型创建的任何对象的某些属性/功能。
--
模型 - 在 Rails 中 - 构建填充您的应用程序的 objects。 Ruby 是一个object orientated language,这意味着您程序的每个元素都应该在某种程度上围绕数据对象。
正如您在上面看到的,在系统中构建对象的方法实际上是调用类。这些类包含方法,可以在类级别(IE通过方法调用类)或实例级别(IE在已调用的对象上调用方法)。
您可以从以下位置获得"class" methods (Model.method) and "instance" methods (@model.method):
#app/models/patient.rb
class Patient < ActiveRecord::Base
def explode
#this is an instance method
puts "Instance Explode"
end
def self.explode
#this is a class method
puts "Exploded"
end
end
因此您可以调用以下代码:
@patient = Patient.find params[:id]
@patient.explode #-> "Instance explode"
Patient.explode #-> "Exploded"
--
这很重要,因为它为您提供了一个严格的框架,说明您应该在模型中的哪些位置使用方法。
它解释了为什么你有 controllers 和 helpers,并允许你制定构建应用程序的最佳方式,以充分利用最少的代码。
例如...
您对@patient.name = params[:params][:name].name_fix 的使用不正确。
这是错误的,因为您在与您的模型完全无关的数据上调用 instance 方法 .name_fix。如果你想像这样在一般意义上使用.name_fix,你可能会使用helper:
#app/helpers/patients_helper.rb
class PatientsHelper
def name_fix value
# stuff here
end
end
#app/controllers/patients_controller.rb
class PatientsController < ApplicationController
def create
@patient.name = name_fix params[:patient][:name]
end
end
由于您使用该方法来填充模型的 .name 属性,因此覆盖 name= 设置器是有意义的。这不仅会提供额外的功能,而且比任何其他方式都更加流畅和高效。