简体   繁体   English

设置虚拟属性Rails活动模型

[英]Set Virtual Attribute Rails Active Model

How do I set a virtual attribute that sets the first and last name, when I call Quote.new()? 调用Quote.new()时,如何设置用于设置名字和姓氏的虚拟属性?

The before_save :assign_name method does not seem work. before_save:assign_name方法似乎不起作用。 I get an error 我得到一个错误

NoMethodError: undefined method `before_save' for Quote:Class

CONTROLLER: 控制器:

  quote = {name: "John Doe", City: "New York"}
  Quote.new(quote) 

MODEL: 模型:

class Quote
    include ActiveModel::Model

    before_save :assign_name

    attr_accessor :name, :first, :last, :city


    def assign_name
      title_split = self.name.split(" / ")
      self.first = title_split[0]
      self.last = title_split[1]
    end
end

You can use something like this 你可以用这样的东西

class Quote
  include ActiveModel::Model
  attr_accessor :name, :first, :last, :city

  def initialize(attributes={})
    super
    assign_name(name)
  end

  def assign_name(name)
    title_split = name.split(" / ")
    self.first = title_split[0]
    self.last = title_split[1]
  end
end

Also link to documentation here 也可以在此处链接到文档

before_save is defined in ActiveRecord. 在ActiveRecord中定义了before_save You need to let your class inherit from ActiveRecord::Base as the following: 您需要让您的类继承自ActiveRecord :: Base,如下所示:

class Quote < ActiveRecord::Base
end

And if you put the method in "before_save" callback, that means the method will be called only when Quote#save is executed. 并且,如果将方法放在“ before_save”回调中,则意味着仅在执行Quote#save时才调用该方法。 For example, 例如,

quote = {name: "John Doe", City: "New York"}
q = Quote.new(quote)
q.save   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM