2013-05-10 109 views
0

我是Rails的新手,基本上和其他人一样,在我的脑海里也有同样的问题。我想链接两个表。但我做不到。帮助我o'mighty stackoverflow用户。Rails has_many belongs_to associations

用户等级:

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 

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

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

,并让和错误,有没有任何其他方法或Ruby代码链接这些表?

+0

有您在数据库中创建的两个之间的链接表? – 2013-05-10 11:39:21

+2

如果它是1:n关联,则不需要额外的表。 foreign_key位于posts table =>请参阅Post model attr_accessible:user_id =>以便表格可以正常工作。 – Mattherick 2013-05-10 11:42:29

回答

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 

你可以阅读更多关于查询的位置:

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. 

如果你有一个使用current_user方法=>返回当前登录的用户,你可以简单的拿他的职位有:

@posts = current_user.posts 
+0

但是,如果我做用户。first.posts并获得帖子,我怎么能得到关于哪个用户写这篇文章的信息?在帖子中有一个user_id属性btw – Yagiz 2013-05-10 11:48:11

+0

我更新了我的答案。欲了解更多信息,请查看链接,了解活动记录的工作原理。 – Mattherick 2013-05-10 11:51:13

+0

谢谢,但你误会了。假设我在控制器中使用了User.all.posts(不知道语法是否正确),并在“显示所有帖子”页面中显示新闻和相应作者的详细信息。我怎样才能做到这一点? – Yagiz 2013-05-10 11:54:04

3
@allposts = Users.Posts.all 

这必须

@allposts= Post.all 

如果你希望某个特定用户的帖子,创建一个用户,然后执行:

User.first.posts 

如果你想获得的所有帖子和属于他们的用户信息不需要额外查询,请尝试:

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

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

1
@allusers = User.all 

收集所有帖子

@allposts = [] 

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

为了收集特定用户的帖子(在这里显示了第一用户)

@allposts = User.first.posts 
+0

不容易复杂,并在你的例子allposts和allpost实例变量是不一样的。你的第一个岗位是简单的Post.all,你的第二个岗位是正确的,但只返回来自第一个用户的帖子,而不是帖子表中的所有帖子。 – Mattherick 2013-05-10 11:56:22

+0

是不是太耗费资源?有没有更有效的方法在铁轨?或者它是唯一的方法 – Yagiz 2013-05-10 11:58:49

+0

检查我的答案中的链接.. – Mattherick 2013-05-10 12:02:59