【问题标题】:Virtual attributes with Devise in Rails 4在 Rails 4 中使用 Devise 的虚拟属性
【发布时间】:2013-09-29 17:26:23
【问题描述】:

我的用户模型没有:name 字段,但我想在我的注册表单中包含一个:name 字段,该字段将用于在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

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

【问题讨论】:

标签: ruby-on-rails ruby devise ruby-on-rails-4 virtual-attribute


【解决方案1】:

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

attr_accessor :name

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

【讨论】:

  • @thing.name = 应该输入什么?
  • self.name 将从控制器传递回模型的任何内容中提取
【解决方案2】:

正如@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

【讨论】:

  • 如果你的 rails 4 你需要将参数添加到强大的参数中,否则如果你使用 rails 3 你需要一个 attr_accessible。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多