设置虚拟属性Rails活动模型

时间:2015-12-19 22:57:28

标签: ruby-on-rails ruby ruby-on-rails-4 activemodel

当我调用Quote.new()时,如何设置设置名字和姓氏的虚拟属性?

before_save:assign_name方法似乎不起作用。我收到错误

NoMethodError: undefined method `before_save' for Quote:Class

控制器:

  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

2 个答案:

答案 0 :(得分:1)

你可以使用这样的东西

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

还链接到文档here

答案 1 :(得分:0)

before_save在ActiveRecord中定义。您需要让您的类继承ActiveRecord :: Base,如下所示:

class Quote < ActiveRecord::Base
end

如果你把方法放在“before_save”回调中,这意味着只有在执行Quote#save时才会调用该方法。例如,

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