0

我有一个独立的学生表,最后一个学生的 Student id: 24.

我有一个帖子表,我将student_id(帖子表上的属性)分配给24

当我做

Student.last.posts 

我得到一个空数组

 => #<ActiveRecord::Associations::CollectionProxy []> 

我实际上期待 post 表中的特定记录(我分配给最后一个学生出现)

那个特定的帖子记录:

=> #<Post id: 9, message: "朱迪是一个不错的房东她总是让我做饭她得到了一台电视和安装电缆并没有问我们凑钱", student_id: 24, created_at: "2013-09-12 14:18:41", updated_at: "2013-09-12 14:51:26", host_id: 1> 
2.0.0-p195 :004 > 

有一个 host_id: 1 因为我在 rails 控制台中创建了一个条目(到第一个主机)

Host.first.posts.create(:message => "朱迪是一个不错的房东她总是让我做饭她得到了一台电视和安装电缆并没有问我们凑钱")

我的 host.rb 模型有

has_many :posts
belongs_to :student 

我的 student.rb 模型有

has_many :hosts
has_many :posts, through: :hosts

我的 post.rb 模型有

belongs_to :student 
belongs_to :host

在我看来,我已经成功地查询出那个特定主人的特定帖子(对寄宿家庭的评论)。我的下一步是显示谁为该特定主机发布了该特定帖子。student_id 应该是 Student id 还是 Student_id ?不知道这是否有帮助?

4

1 回答 1

0

根据您的模型,您的主机必须有一个 student_id。从您的示例中不清楚,但您在 Host.first 中的 student_id 似乎不是 Student.last.id。

@kobaltz 评论提到的另一点是您的 Post 模型具有 host_id 和 student_id。这看起来像您将其用作关联。所以你的模型应该看起来像这样。

post.rb

belongs_to :host
belongs_to :student

学生.rb

has_many :posts
has_many :hosts, :through => :posts

主机.rb

has_many :posts
has_many :students, :through => :posts
于 2013-09-12T17:32:24.907 回答