質問

これは少し前に話題になりました( Railsモデル属性にデータベースに対応する列がありません )しかし、言及されているRailsプラグインはメンテナンスされていないようです( http://agilewebdevelopment.com/plugins/activerecord_base_without_table )。このままActiveRecordでやる方法はないのでしょうか?

そうでない場合、ActiveRecord を使用せずに ActiveRecord 検証ルールを取得する方法はありますか?

もちろん、ActiveRecord はテーブルが存在することを望んでいます。

役に立ちましたか?

解決

これは、私が過去に使用しているアプローチです。

でのアプリ/モデル/ 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>>

他のヒント

の検証は、単にActiveRecordの内のモジュールです。あなたは非ActiveRecordのモデルにそれらを混合したことがありますか?

class MyModel
  include ActiveRecord::Validations

  # ...
end
「テーブルのないレール3.1モデル」

を検索する際に、これはGoogleの最初の結果の一つであるため、

私はより多くの回答をよりよく理解します ActiveRecordの検証::

を含めて

私はActiveRecordの::ベースを使用せずに同じことを実現しました

主な目標は、すべてがformtasticでの作業を取得した、と私はどこにも保存されませうサンプルの支払いを含め、まだ我々はすべて知っているの検証と愛を使用して検証する能力を持っていました下記ます。

class Payment
  include ActiveModel::Validations
  attr_accessor :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state, :zip_code, :home_telephone, :email, :new_record

  validates_presence_of :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state

  def initialize(options = {})
    if options.blank?
      new_record = true
    else
      new_record = false
    end
    options.each do |key, value|
      method_object = self.method((key + "=").to_sym)
      method_object.call(value)
    end
  end

  def new_record?
    return new_record
  end

  def to_key
  end

  def persisted?
    return false
  end
end

私は今日これを理解しようとしているいくつかの時間を費やしてきたように、これは誰かに役立ちます願っています。

アップデート: Rails 3 の場合、これは非常に簡単に行うことができます。Rails 3 以降では、新しい ActiveModel モジュールとそのサブモジュール。これで動作するはずです:

class Tableless
  include ActiveModel::Validations

  attr_accessor :name

  validates_presence_of :name
end

詳細については、以下をご覧ください。 レールキャスト (または AsciiCast でそれについて読む)このトピックとこれについて Yehuda Katz によるブログ投稿.

古い答えは次のとおりです:

前のコメントで John Topley によって提案されたソリューションにこれを追加する必要がある場合があります。

class Tableless

  class << self
    def table_name
      self.name.tableize
    end
  end

end

class Foo < Tableless; end
Foo.table_name # will return "foos"

これにより、必要に応じて「偽の」テーブル名が提供されます。この方法がなければ、 Foo::table_name 「テーブルレス」と評価されます。

私美しく動作します。このリンクを発見しました。

http://codetunes.com/2008/07/ 20 /テーブルなし-モデル・イン・レール/

受け入れ答えにだけ加えます:

あなたのサブクラスは親に列を継承してください。

class FakeAR < ActiveRecord::Base
  def self.inherited(subclass)
    subclass.instance_variable_set("@columns", columns)
    super
  end

  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

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

これは終了の期間のオブジェクトを持っているの基準のと呼ばれるオブジェクトを提示し、検索フォームですem>の属性ます。

コントローラ内のアクションは本当に単純でまだそれはフォームにネストされたオブジェクトの値を読み込み、必要に応じて、エラーメッセージと同じ値を再描画する。

のRails 3.1で動作します。

モデル:

class Criteria < ActiveRecord::Base
  class << self

    def column_defaults
      {}
    end

    def column_names
      []
    end
  end # of class methods

  attr_reader :period

  def initialize values
    values ||= {}
    @period = Period.new values[:period] || {}
    super values
  end

  def period_attributes
    @period
  end
  def period_attributes= new_values
    @period.attributes = new_values
  end
end

コントローラで

def search
  @criteria = Criteria.new params[:criteria]
end

ヘルパーでます:

def criteria_index_path ct, options = {}
  url_for :action => :search
end

鑑みます:

<%= form_for @criteria do |form| %>
  <%= form.fields_for :period do |prf| %>
    <%= prf.text_field :beginning_as_text %>
    <%= prf.text_field :end_as_text %>
  <% end %>
  <%= form.submit "Search" %>
<% end %>

HTMLを生成します:

<form action="/admin/search" id="new_criteria" method="post">
  <input id="criteria_period_attributes_beginning_as_text" name="criteria[period_attributes][beginning_as_text]" type="text"> 
  <input id="criteria_period_attributes_end_as_text" name="criteria[period_attributes][end_as_text]" type="text">

:ヘルパーと一度にすべての値をロードするようにコントローラのためのそれはとても簡単になります形式を命名するネストされた属性によって提供さaction属性

のActiveRecord-テーブルなしの宝石のがあります。これは、テーブルなしActiveRecordのモデルを作成するための宝石ですので、検証、団体、種類をサポートしています。これは、Active Recordの2.3、3.0、3.2

をサポートしています

(ActiveModelを使用して)Railsの3.xの中でそれを行うために推奨される方法は、団体や種類をサポートしていません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top