0

我是 Rails 的新手,基本上和其他人一样,我也有同样的问题。我想将两个表相互链接。但我做不到。帮助我强大的stackoverflow用户。

用户类:

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

帖子类:

class Post < ActiveRecord::Base
  attr_accessible :details, :title, :user_id, :picture
  belongs_to :user
end

在终端中,我登录到 rails 控制台并说:

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

它给出了错误,是否有任何其他方法或 Ruby 代码来链接这些表?

4

3 回答 3

5

这取决于你想要什么结果:

@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

您可以在此处阅读有关查询的更多信息:

更新

@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.

如果你有一个 current_user 方法 => 返回当前登录用户,你可以简单地获取他的帖子:

@posts = current_user.posts
于 2013-05-10T11:41:20.013 回答
3
@allposts = Users.Posts.all

这需要

@allposts= Post.all

如果您想要特定用户的帖子,请创建一个用户,然后执行以下操作:

User.first.posts

如果您想在不进行额外查询的情况下获取所有帖子和属于它们的用户信息,请尝试:

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

这种方式@allposts.first.user不会导致额外的查询。

于 2013-05-10T11:40:20.203 回答
1
@allusers = User.all

收集所有帖子

@allposts = []

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

收集特定用户的帖子(此处为第一个用户显示)

@allposts = User.first.posts
于 2013-05-10T11:52:26.413 回答