Forum: Ruby on Rails ActiveRecord and model question

236dd7ca555806d7c971f1af1523a3d5?d=identicon&s=25 Srdjan Cengic (Guest)
on 2013-10-20 19:41
(Received via mailing list)
Hy,

I have some table in my DB like following: *Post(id, title, content,
created_at, updated_at)*

First question, what type ActiveRecord returns?
For example if i do something like: @posts = Post.all, through debugger
i
can see:

#<ActiveRecord::Relation
*[*#<Post id: 1, title: "My first post", content: "Zdravo, ovo je moj
prvi
post.", created_at: "2013-10-17 10:06:55", updated_at: "2013-10-17
10:06:55">,
#<Post id: 3, title: "My second post", content: "Zdravo, ovo je moj
drugi
post.", created_at: "2013-10-17 11:11:29", updated_at: "2013-10-17
11:11:29">,
#<Post id: 18, title: "My third post", content: "Dobar dan, ovo je moj
treci post.", created_at: "2013-10-18 11:31:07",updated_at: "2013-10-18
11:31:07">*]*>

So this is array of hashes? or array of Post objects?

Second if i do something like:
@post = Post.first (this will return Post object?)

then through debugger i can do: @post.id
Here, i'm guessing, because each model is inherit from
ActiveRecord::Base,
ActiveRecord will create accessor for each column in table that
represent
model?
Because that i can write something like @post.id or @post.id = 100.
So internally ActiveRecord does something like attr_accessor :id for
Post
model? (and for every other column in posts table, attr_accesor: title,
etc)
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2013-10-20 19:46
(Received via mailing list)
On Saturday, October 19, 2013 7:33:12 PM UTC+1, Srdjan Cengic wrote:
> #<ActiveRecord::Relation
> So this is array of hashes? or array of Post objects?
>
> I n rails 3, this is an array of Post objects (on rails 4 it is an
ActiveRecord::Relation, but you can still treat it as an array of Post
objects)


> Second if i do something like:
> @post = Post.first (this will return Post object?)
>
> Yes.

then through debugger i can do: @post.id
> Here, i'm guessing, because each model is inherit from ActiveRecord::Base,
> ActiveRecord will create accessor for each column in table that represent
> model?
> Because that i can write something like @post.id or @post.id = 100.
> So internally ActiveRecord does something like attr_accessor :id for Post
> model? (and for every other column in posts table, attr_accesor: title, etc)
>

ActiveRecord creates accessors for you (although they are not the same
as
the ones that would be created by attr_accessor)

Fred
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.