简体   繁体   English

Ruby目前的模型不在DB中

[英]Ruby present model not in DB

I would like to use a model in Rails but not store it in DB. 我想在Rails中使用模型但不将其存储在DB中。 For example let's say I have a RSS reader. 例如,假设我有一个RSS阅读器。 I would download some RSS data from other site and then create objects with specific model and show them to use. 我会从其他站点下载一些RSS数据,然后创建具有特定模型的对象并显示它们以供使用。 I don't want to store those objects in databse though. 我不想将这些对象存储在数据库中。 How can I do it? 我该怎么做?

I think your problem might easily be solved by just creating a class, alternatively you can use ActiveModel, it allows for the same behaviour without storing it in the db. 我认为你的问题很容易通过创建一个类来解决,或者你可以使用ActiveModel,它允许相同的行为而不将其存储在db中。

class RssReader
  #include any behaviour you like
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming
end

There is a very nice railscast on this at: 这里有一个非常好的轨道广播:

You can also check this out(Rails 4) 你也可以看一下(Rails 4)

You're looking for tableless models, there are plenty of questions on SO about this: 您正在寻找无表格模型,关于此问题有很多问题:

and a handy railscast! 和一个方便的railscast!

In rails 2.3 You can do this by this way: 在rails 2.3中你可以这样做:

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


  column :orderable_id, :integer
  column :orderable_type, :string
  column :subscription, :boolean
  column :interval, :integer
  column :quantity, :float
  column :number, :integer
  column :only_with_main_cart, :boolean
  column :start_on, :date

  attr_accessor :choice_item
  attr_accessor :interval_choice_item_1
  attr_accessor :interval_choice_item_2
  validates_presence_of :orderable_id
  validates_presence_of :orderable_type
  validates_presence_of :interval
  validates_numericality_of :quantity, :greater_than => 0
  validates_inclusion_of :subscription, :in => [true, false]
  validates_inclusion_of :only_with_main_cart, :in => [true, false]

end

I am using this for storing cart information before user confirmation 我在用户确认之前用它来存储购物车信息

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

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