Ruby on rails 保存父项';从孩子的关系

Ruby on rails 保存父项';从孩子的关系,ruby-on-rails,model,parent,Ruby On Rails,Model,Parent,我有以下关系。我想要一个帖子有一个当前的wrent,但也有很多wrent,可以跟踪wrent对象。我相信这个问题可能与rails混淆了我所指的关系有关 当我引用post.current\u wrent时,它将正确返回,没有错误 Class Post include Mongoid::Document include Mongoid::Timestamps ... has_one :current_wrent, :class_name => "Wrent", :inverse_of =

我有以下关系。我想要一个帖子有一个当前的wrent,但也有很多wrent,可以跟踪wrent对象。我相信这个问题可能与rails混淆了我所指的关系有关

当我引用post.current\u wrent时,它将正确返回,没有错误

Class Post

include Mongoid::Document
include Mongoid::Timestamps
  ...
has_one :current_wrent, :class_name => "Wrent", :inverse_of => :current_wrent, :autosave => true, :dependent => :destroy
has_many :wrents, :inverse_of => :post, :dependent => :destroy
end

Class Wrent
..
belongs_to :post, :autosave => true
..
end
当我做类似于。。 (单位:Wrent.rb)

我得到一个“当前Wrent”是无效错误,有人能指出我做错了什么吗

编辑:这似乎很好用。 在wrent.rb中

Class Wrent
  ..
  belongs_to :post, :inverse_of => :wrent, :autosave => true
  belongs_to :post, :inverse_of => :current_wrent
在post.rb中 班岗 ...

  has_one :current_wrent, :class_name => "Wrent", :inverse_of => :post
  belongs_to :current_wrent, :class_name => "Wrent", :inverse_of => :post
  has_many :wrents, :inverse_of => :post, :dependent => :destroy

我仍然不确定问题是什么,但现在我可以通过“属于当前”列访问post.current\u-rent\u-id,问题似乎消失了。

您的wrent模型可能有一个post\u-id字段,其中存储了它所属帖子的id。但是Post中没有存储当前事件的字段。 Mongoid允许你嵌入对象,所以你能做的是嵌入一个而不是一个

Class Post

  include Mongoid::Document
  include Mongoid::Timestamps
  ...
  embeds_one :current_wrent, :class_name => "Wrent", :inverse_of => :current_wrent
  has_many :wrents, :inverse_of => :post, :dependent => :destroy
end

你能发布错误的完整堆栈跟踪吗?我没有堆栈跟踪,但它最后做的是post.save!并且,这导致它崩溃并返回错误“Validation failed:Current\u wrent is invalid”。这个问题与当前wrent关系定义hanks的方式有关,但我想我不想将其嵌入其中-除非我访问根文档,否则我不能随意删除、访问或修改wrent对象,这是我不想做的。我仍然希望能够使用Wrent.find或Wrent.create,据我所知,将其嵌入单个对象中可以防止在其他地方访问它。在这种情况下,您将需要一个“属于”:Post类中的“当前”Wrent而不是“一个”来存储当前的Wrent对象id。这正是我决定的。谢谢你的帮助!
Class Post

  include Mongoid::Document
  include Mongoid::Timestamps
  ...
  embeds_one :current_wrent, :class_name => "Wrent", :inverse_of => :current_wrent
  has_many :wrents, :inverse_of => :post, :dependent => :destroy
end