[英]Virtual attributes with Devise in Rails 4
My User model doesn't have a :name
field but I want to include a :name
field in my sign up form which will be used to create a record of another model in an after_create
. 我的用户模型没有:name
字段,但我想在我的注册表单中包括:name
字段,该字段将用于在after_create
创建另一个模型的after_create
。
class User < ActiveRecord::Base
after_create :create_thing
private
def create_thing
@thing = Thing.new
@thing.name = <here's where I need help>
@thing.save!
end
end
How can I get the name from the sign up form? 如何从注册表单中获取姓名?
In your model add attr_accessor for name 在模型中,添加attr_accessor作为名称
attr_accessor :name
This will allow you to add it to a form and use it to generate the proper data in your after_create 这将允许您将其添加到表单中,并使用它在after_create中生成正确的数据
Just as @trh said you can use a attr_accessor, but if you need to have it do some logic your gonna need to make getter and/or setter methods to accompany the attr_accessor. 就像@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.