使用Rails中的Devise创建虚拟属性4

我的用户模型没有:name字段,但我想在我的注册表单中包含:name字段,该字段将用于在after_create创建另一个模型的after_create

 class User < ActiveRecord::Base after_create :create_thing private def create_thing @thing = Thing.new @thing.name =  @thing.save! end end 

如何从注册表单中获取名称?

在您的模型中为名称添加attr_accessor

 attr_accessor :name 

这将允许您将其添加到表单并使用它在after_create中生成正确的数据

就像@trh说你可以使用attr_accessor一样,但是如果你需要让它做一些逻辑,你需要使用getter和/或setter方法来配合attr_accessor。

 class User < ActiveRecord::Base attr_accessor :name after_create :create_thing def name #if need be do something to get the name "#{self.first_name} #{self.last_name}" end def name=(value) #if need be do something to set the name names = value.split @first_name = names[0] @last_name = names[1] end private def create_thing @thing = Thing.new @thing.name = self.name @thing.save! end end