跳至内容 跳至搜索

ActiveModel 是一个由每个 ORM 实现的类,允许 Rails 生成自定义的控制器代码。

APIActiveRecord 的方法相同,但每个方法都返回一个与 ORM API 匹配的字符串。

例如

ActiveRecord::Generators::ActiveModel.find(Foo, "params[:id]")
# => "Foo.find(params[:id])"

DataMapper::Generators::ActiveModel.find(Foo, "params[:id]")
# => "Foo.get(params[:id])"

在初始化时,ActiveModel 接受将接收调用的实例名称

builder = ActiveRecord::Generators::ActiveModel.new "@foo"
builder.save # => "@foo.save"

对于 ActiveRecordActiveModel 中唯一的例外是使用 self.build 而不是 self.new。

方法
A
B
D
E
F
N
S
U

属性

[R] name

类公共方法

all(klass)

用于

  • GET index

# File railties/lib/rails/generators/active_model.rb, line 38
def self.all(klass)
  "#{klass}.all"
end

build(klass, params = nil)

用于

  • GET new

  • POST create

# File railties/lib/rails/generators/active_model.rb, line 56
def self.build(klass, params = nil)
  if params
    "#{klass}.new(#{params})"
  else
    "#{klass}.new"
  end
end

find(klass, params = nil)

用于

  • GET show

  • GET edit

  • PATCH / PUT update

  • DELETE destroy

# File railties/lib/rails/generators/active_model.rb, line 48
def self.find(klass, params = nil)
  "#{klass}.find(#{params})"
end

new(name)

# File railties/lib/rails/generators/active_model.rb, line 31
def initialize(name)
  @name = name
end

实例公共方法

destroy()

用于

  • DELETE destroy

# File railties/lib/rails/generators/active_model.rb, line 89
def destroy
  "#{name}.destroy!"
end

errors()

用于

  • POST create

  • PATCH / PUT update

# File railties/lib/rails/generators/active_model.rb, line 82
def errors
  "#{name}.errors"
end

save()

用于

  • POST create

# File railties/lib/rails/generators/active_model.rb, line 67
def save
  "#{name}.save"
end

update(params = nil)

用于

  • PATCH / PUT update

# File railties/lib/rails/generators/active_model.rb, line 74
def update(params = nil)
  "#{name}.update(#{params})"
end