简体   繁体   English

Rails has_many属于_关联

[英]Rails has_many belongs_to associations

I am new to Rails and basically, as others, have the same question in my mind. 我是Rails的新手,与其他人一样,基本上我也有相同的问题。 I want to link two tables to each other. 我想将两个表相互链接。 But I couldn't do it. 但是我做不到。 Help me o'mighty stackoverflow users. 帮助我强大的stackoverflow用户。

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: 在终端中,我登录Rails控制台并说:

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

And it gives and error, are there any other method or Ruby code to link these tables? 它给出错误,是否还有其他方法或Ruby代码链接这些表?

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: 如果您有current_user方法=>返回当前登录的用户,则可以使用以下命令简单地获取其帖子:

@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. 这样@allposts.first.user不会引起额外的查询。

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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