I have created two tables in my db. The first table is users
, with columns:
id, name
The second table is microposts
, with columns:
id, content, user_id
This is my Micropost
model
class Micropost < ActiveRecord::Base
belongs_to :user
validates :content, length: { maximum:20 }
end
and this is the index method in my MicropostController
def index
@microposts = Micropost.all
end
when I check in index view like this
<%= debug @microposts %>
I get this result
---
- !ruby/object:Micropost
attributes:
id: 1
content: new micropost
user_id: 1
created_at: 2014-04-12 10:56:04.000000000 Z
updated_at: 2014-04-12 10:56:04.000000000 Z
I am not getting user table data with relation. How can i do this?
This is the User
model:
class User < ActiveRecord::Base
has_many :micropost
end
If you want to get the user who has the micropost
, you should use micropost.user
. For example: @microposts.first.user
will return the user of @microposts's first record.