Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2|
Lessons:- A User has many Microposts

 

  We can visualize the result of this association in Figure 2.15. Because of the user_id column in the microposts table, Rails (using Active Record) can infer the microposts associated with each user.

In Chapter 10 and Chapter 11, we will use the association of users and microposts both to display all a user’s microposts and to construct a Twitter-like micropost feed. For now, we can examine the implications of the user-micropost association by using

the console, which is a useful tool for interacting with Rails applications. We first invoke the console with rails console at the command line, and then retrieve the first user from the database using User.first (putting the results in the variable first_user):7

$ rails console
>> first user = User.first
=> #<User id: 1, name: "Michael Hartl", email: "michael@example.org",
created at: "2011-11-03 02:01:31", updated at: "2011-11-03 02:01:31">

>> first user.microposts
=> [#<Micropost id: 1, content: "First micropost!", user id: 1, created at:
"2011-11-03 02:37:37", updated at: "2011-11-03 02:37:37">, #<Micropost id: 2,
content: "Second micropost", user id: 1, created at: "2011-11-03 02:38:54",
updated at: "2011-11-03 02:38:54">]

>>  exit

(I include the last line just to demonstrate how to exit the console, and on most systems you can Ctrl-d for the same purpose.) Here we have accessed the user’s microposts using the code first_user.microposts: With this code, Active Record automatically returns all the microposts with user_id equal to the id of first_user (in this case, 1). We’ll learn much more about the association facilities in Active Record in Chapter 10 and Chapter 11.  

 
 
 
image
Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student
Explore
 

  Students (0)