Program Club

데이터베이스가없는 Rails 모델

proclub 2020. 11. 16. 22:22
반응형

데이터베이스가없는 Rails 모델


ActiveRecord 유효성 검사를 사용하지만 데이터베이스 테이블없이 Rails (2.1 및 2.2) 모델을 만들고 싶습니다. 가장 널리 사용되는 접근 방식은 무엇입니까? 이 기능을 제공한다고 주장하는 일부 플러그인을 찾았지만 그 중 상당수가 널리 사용되거나 유지되지 않는 것으로 보입니다. 커뮤니티에서 권장하는 작업은 무엇입니까? 지금은 이 블로그 게시물을 기반으로 자체 솔루션을 찾는쪽으로 기울고 있습니다.


링크하고있는 블로그 게시물이 가장 좋은 방법이라고 생각합니다. 코드를 오염시키지 않도록 stubbed 메서드를 모듈로 이동하는 것이 좋습니다.


Rails 3에서 더 좋은 방법이 있습니다 . http://railscasts.com/episodes/219-active-model


이것은 내가 과거에 사용한 접근 방식입니다.

에서 응용 프로그램 / 모델 / tableless.rb

class Tableless < ActiveRecord::Base
  def self.columns
    @columns ||= [];
  end

  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default,
      sql_type.to_s, null)
  end

  # Override the save method to prevent exceptions.
  def save(validate = true)
    validate ? valid? : true
  end
end

에서 응용 프로그램 / 모델 / foo.rb

class Foo < Tableless
  column :bar, :string  
  validates_presence_of :bar
end

에서 스크립트 / 콘솔

Loading development environment (Rails 2.2.2)
>> foo = Foo.new
=> #<Foo bar: nil>
>> foo.valid?
=> false
>> foo.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>

이제 더 쉬운 방법이 있습니다.

class Model
  include ActiveModel::Model

  attr_accessor :var

  validates :var, presence: true
end

ActiveModel::Model 암호:

module ActiveModel
  module Model
    def self.included(base)
      base.class_eval do
        extend  ActiveModel::Naming
        extend  ActiveModel::Translation
        include ActiveModel::Validations
        include ActiveModel::Conversion
      end
    end

    def initialize(params={})
      params.each do |attr, value|
        self.public_send("#{attr}=", value)
      end if params
    end

    def persisted?
      false
    end
  end
end

http://api.rubyonrails.org/classes/ActiveModel/Model.html


"models /"디렉토리에서 익숙한 규칙 (파일 이름과 클래스 이름은 단수, 파일 이름은 밑줄, 클래스 이름은 낙타 대문자)에 따라 ".rb"로 끝나는 새 파일을 만듭니다. 여기서 핵심은 ActiveRecord에서 모델을 상속하지 않는 것입니다 (데이터베이스 기능을 제공하는 것이 AR이기 때문입니다). 예 : 자동차 용 새 모델의 경우 models / 디렉토리와 모델 내부에 "car.rb"라는 파일을 만듭니다.

class Car
    # here goes all your model's stuff
end

편집 : btw, 클래스에 대한 속성을 원한다면 여기에서 루비에서 사용하는 모든 것을 사용할 수 있습니다. "attr_accessor"를 사용하여 몇 줄만 추가하면됩니다.

class Car
    attr_accessor :wheels # this will create for you the reader and writer for this attribute
    attr_accessor :doors # ya, this will do the same

    # here goes all your model's stuff
end

edit #2: after reading Mike's comment, I'd tell you to go his way if you want all of the ActiveRecord's functionality but no table on the database. If you just want an ordinary Ruby class, maybe you'll find this solution better ;)


For the sake of completeness:

Rails now (at V5) has a handy module you can include:

include ActiveModel::Model

This allows you to initialise with a hash, and use validations amongst other things.

Full documentation is here.


There's a screencast about non-Active Record model, made up by Ryan Bates. A good place to start from.

Just in case you did not already watch it.


I have built a quick Mixin to handle this, as per John Topley's suggestion.

http://github.com/willrjmarshall/Tableless


What about marking the class as abstract?

class Car < ActiveRecord::Base
  self.abstract = true
end

this will tell rails that the Car class has no corresponding table.

[edit]

this won't really help you if you'll need to do something like:

my_car = Car.new

Use the Validatable gem. As you say, there are AR-based solutions, but they tend to be brittle.

http://validatable.rubyforge.org/


Anybody has ever tried to include ActiveRecord::Validations and ActiveRecord::Validations::ClassMethods in a non-Active Record class and see what happens when trying to setup validators ?

I'm sure there are plenty of dependencies between the validation framework and ActiveRecord itself. But you may succeed in getting rid of those dependencies by forking your own validation framework from the AR validation framework.

Just an idea.

Update: oopps, this is more or less what's suggested in the post linked with your question. Sorry for the disturbance.


Do like Tiago Pinto said and just don't have your model inherit from ActiveRecord::Base. It'll just be a regular Ruby class that you stick in a file in your app/models/ directory. If none of your models have tables and you're not using a database or ActiveRecord at all in your app, be sure to modify your environment.rb file to have the following line:

config.frameworks -= [:active_record]

This should be within the Rails::Initializer.run do |config| block.


You ought to checkout the PassiveRecord plugin. It gives you an ActiveRecord-like interface for non-database models. It's simple, and less hassle than fighting ActiveRecord.

We're using PassiveRecord in combination with the Validatable gem to get the OP's desired behaviour.

참고URL : https://stackoverflow.com/questions/315850/rails-model-without-database

반응형