Tim Hui
Tim Hui

Reputation: 125

saving a parent's relationship from child

I have the following relationship. I want a Post to has_one current_wrent but also has_many wrents that keeps tracks of wrent objects. I believe the issue may be related to rails being confused which relationship i'mr eferring to.

When I refer to a post.current_wrent, this is returning correctly with no errors.

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

When I do something like.. (in Wrent.rb)

def accept!
  update_attributes!(:status => 1, :accepted => true) 
  post.current_wrent = self
  post.available = false
  post.save!
  notify_user
end

and I get a "Current Wrent" is invalid error, could somebody point to me something I'm doing wrong here?

EDIT: this seems to work fine. in wrent.rb

Class Wrent
  ..
  belongs_to :post, :inverse_of => :wrent, :autosave => true
  belongs_to :post, :inverse_of => :current_wrent

in post.rb Class Post ...

  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

I'm still not sure what the problem is, but now I can access post.current_wrent through the belongs_to current_wrent_id column and the problem seemed to disappear.

Upvotes: 0

Views: 115

Answers (1)

Rafael Fiuza
Rafael Fiuza

Reputation: 21

Your Wrent model probably has a post_id field where is stored the id of the Post that it belongs_to. But there's no field in Post to store the current_wrent. Mongoid allows you to embed objects so what you can do is embeds_one instead has_one.

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

Upvotes: 1

Related Questions