2

我的用户模型没有:name字段,但我想在我的注册表单中包含:name字段,该字段将用于在after_create中创建另一个模型的记录。虚拟属性与Devise in Rails 4

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 

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

+0

我的标题可能是错的,所以请随时提出一个更好的建议。 –

+0

我在这里找到了我的答案:http://stackoverflow.com/a/17384426/519632 –

回答

4

在模型中添加attr_accessor的名字

attr_accessor :name 

这将允许你将它添加到一个表单和@trh说,你可以用它在你的after_create生成适当的数据

+0

什么应该进入'@thing.name ='? –

+0

'self.name'将从控制器返回到模型的任何东西拉动 – trh

+0

我收到Unpermitted参数错误:http://pastebin.com/V1gmsP6a –

2

刚使用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 
+0

我收到Unpermitted参数错误:http://pastebin.com/V1gmsP6a –

+0

如果您的rails 4您需要将params添加到强参数,否则如果您使用rails 3,则需要attr_accessible。 –