簡體   English   中英

Devise in Rails 4中的虛擬屬性

[英]Virtual attributes with Devise in Rails 4

我的用戶模型沒有: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

如何從注冊表單中獲取姓名?

在模型中,添加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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM