Rails has_many belongs_to associations -


i new rails , basically, others, have same question in mind. want link 2 tables each other. couldn't it. me o'mighty stackoverflow users.

users class:

class user < activerecord::base   attr_accessible :password, :username, :oauth_token, :provider, :uid, :oauth_expires_at, :picture, :email, :name, :location, :gender, :updated_at, :is_admin   has_many :posts    end 

posts class:

class post < activerecord::base   attr_accessible :details, :title, :user_id, :picture   belongs_to :user end 

in terminal, log rails console , say:

@allusers = users.all @allposts = users.posts.all 

and gives , error, there other method or ruby code link these tables?

it depends on want result:

@allusers = user.all # returns users of users table @allposts = post.all # returns posts of posts table @user = user.first # returns first user of users table @posts = @user.posts # returns posts of first user of posts table @posts = user.first.posts # returns posts of first user of posts table 

you can read out more querying here:

update

@posts = user.where(:id => 123).first.posts # returns posts of user id 123. => posts of posts table have user_id 123 returned. 

if have current_user method => returns current logged in user, can simple fetch posts with:

@posts = current_user.posts 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -