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。 –