Ruby on rails 如何将现有记录分配给活动记录中的其他记录
我有一个独立的学生表,其中包含最后一个学生,学生id为Ruby on rails 如何将现有记录分配给活动记录中的其他记录,ruby-on-rails,Ruby On Rails,我有一个独立的学生表,其中包含最后一个学生,学生id为24 我有一个post表,其中我将学生id(post表上的属性)分配给24 当我这样做的时候 Student.last.posts 我得到一个空数组 => #<ActiveRecord::Associations::CollectionProxy []> my host.rb模型已更新 has_many :posts belongs_to :student has_many :hosts has_many :p
24
我有一个post表,其中我将学生id
(post表上的属性)分配给24
当我这样做的时候
Student.last.posts
我得到一个空数组
=> #<ActiveRecord::Associations::CollectionProxy []>
my host.rb模型已更新
has_many :posts
belongs_to :student
has_many :hosts
has_many :posts, through: :hosts
belongs_to :student
belongs_to :host
我的student.rb模型
has_many :posts
belongs_to :student
has_many :hosts
has_many :posts, through: :hosts
belongs_to :student
belongs_to :host
我的post.rb模型
has_many :posts
belongs_to :student
has_many :hosts
has_many :posts, through: :hosts
belongs_to :student
belongs_to :host
在我看来,我已经成功地为那个特定的主人查询了那个特定的帖子(关于家庭住宿的评论)。我的下一步是显示谁发布了这个特定主机的特定帖子。学生id应该是学生id还是学生id?不知道这是否有帮助?根据您的模型,您的主机必须有一个学生id。从您的示例中不清楚,但在Host.first中您的学生id似乎不是student.last.id @kobaltz评论提到的另一点是,你的帖子模型有主持人id和学生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
既然一个
学生
通过主机
有许多帖子
,你就不需要像学生.last.hosts.last.posts
或主机上的任何第一个或最后一个帖子那样做吗。否则,请通过::hosts更改您的型号并删除。