Active record Query methods for simple class

7 views
Skip to first unread message

kingston.s

unread,
Feb 2, 2015, 7:16:38 AM2/2/15
to bangal...@googlegroups.com
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.

Vipul A M

unread,
Feb 2, 2015, 7:28:11 AM2/2/15
to bangal...@googlegroups.com
Hi Kingston,

the methods you have listed pertain to records/instances being
persisted to database. All of the queries, expect for a table to be
present,
corresponding to your model. What exactly do you want to achieve here?

PS. Rails now allows assign_attributes[1], so you don't have to do

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

Thanks,
[1] https://github.com/rails/rails/commit/2606fb339797a99c50e531105fc92071cef3db01
Vipul A.M.
+91-8149-204995
> --
> You received this message because you are subscribed to the Google Groups
> "BANGALORE RUG-Ruby Users Group" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to bangalorerug...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

kingston.s

unread,
Feb 2, 2015, 7:34:42 AM2/2/15
to bangal...@googlegroups.com
Thanks Vipul for your reply,

I want to use below methods to use


        where
        limit
        having
        group
        select
        order
        uniq

Thanks,
Kingston.s
Reply all
Reply to author
Forward
0 new messages