简体   繁体   中英

Rails has_many belongs_to associations

I am new to Rails and basically, as others, have the same question in my mind. I want to link two tables to each other. But I couldn't do it. Help 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, I log into rails console and say:

@allusers = Users.all
@allposts = Users.Posts.all

And it gives and error, are there any other method or Ruby code to link these tables?

It depends on what you want as a result:

@allusers = User.all # returns all users of the users table
@allposts = Post.all # returns all posts of the posts table
@user = User.first # returns first user of the users table
@posts = @user.posts # returns all posts of the first user of the posts table
@posts = User.first.posts # also returns all posts of the first user of the posts table

You can read out more about querying here:

UPDATE

@posts = User.where(:id => 123).first.posts # returns all posts of the user with the id 123. => all posts of the posts table which have the user_id 123 will be returned.

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

@posts = current_user.posts
@allposts = Users.Posts.all

This needs to be

@allposts= Post.all

If you want the posts of a specific user, create one user, then do:

User.first.posts

If you want to get all posts and the user information that belongs to them without doing extra queries, try:

@allposts= Post.include(:user).all

This way @allposts.first.user will not cause an extra query.

@allusers = User.all

To Collect all posts

@allposts = []

@allusers.each do |user|
 @posts = user.posts
    @posts.each do |post|
      @allposts << post
    end
end

To collect a specific user's posts (here showing for first user)

@allposts = User.first.posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM