0

I have created class using Active Model,it is working as expected ,but am having few requirements

1) I want to use all method for that class.

2) Same way i want to use some query methods like where method for that class.

3) I want to create ActiveRecord::Relation so that i can do method chaining.

See my class:

require 'active_model'
require 'active_record'


class Message
 include ActiveModel::Validations
 include ActiveModel::Conversion
 extend ActiveModel::Naming

 attr_accessor :name, :email, :content

 validates_presence_of :name
 validates_length_of :content, :maximum => 500

 def initialize(attributes = {})
  attributes.each do |name, value|
   send("#{name}=", value)
  end
 end

 def persisted?
   false
 end
end


 m = Message.new(:email => "test",:name => "test")
 puts m.name   #=> test
 puts m.class  #=> Message
 puts m.valid? #=> true

 Message.all
 Message.where(:name => "test")

some more methods:

 where
 limit
 having
 group
 select
 order
 uniq

Could you please help me to achieve this or give some guide lines.

Jenorish
  • 1,694
  • 14
  • 19
  • 1
    Your class needs to inherit from ActiveRecord::Base – David Feb 02 '15 at 11:45
  • I have verified also it was throwing database connection error,`No connection pool for Run (ActiveRecord::ConnectionNotEstablished)` – Jenorish Feb 02 '15 at 11:51
  • If I understand correctly, your model should behave like an `ActiveRecord` object and it uses SQL DB for data persistance. Therefore, it should inherit from `ActiveRecord::Base`. – Marek Lipka Feb 02 '15 at 11:53
  • Kingston, you need to read up on Ruby on Rails development. Models don't need or use the initialize method. You need to configure a DB (or use the default Sqlite3) and then you need to write a migration file for your model, Message, so that it has the rows you want. After that, you can freely toy with Message as a model. As it stands, you're trying to use a PORO as a Model. – David Feb 02 '15 at 11:55
  • @MarekLipka My class no need to behave like `ActiveRecord`,But i want to use only query methods which should not use sql queries.for that i could create my own methods but that will return `array` or that class object but that method should return `ActiveRecord::Relation`. – Jenorish Feb 02 '15 at 12:04
  • @Kingston they can't return `ActiveRecord::Relation` if they don't use SQL base and `ActiveRecord::Base` models. In this case, you have to create your own solution. – Marek Lipka Feb 02 '15 at 12:12

0 Answers0