如何将现有记录分配给活动记录中的另一个记录

时间:2013-09-12 16:18:49

标签: ruby-on-rails

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

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

当我这样做时

Student.last.posts 

我得到一个空数组

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

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

特定的帖子记录:

=> #<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应该是学生ID还是Student_id?不知道这有帮助吗?

1 个答案:

答案 0 :(得分:0)

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

@kobaltz评论略微提到的另一点是你的Post模型有host_id和student_id。这看起来像是将它用作关联。所以你的模型可能看起来像这样。

post.rb

belongs_to :host
belongs_to :student

student.rb

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

host.rb

has_many :posts
has_many :students, :through => :posts