문제

I'm having trouble using update_attributes with referenced documents. I've reduced my problem to a simple example that AFAICT should work, but doesn't:

class Account
  include Mongoid::Document
  has_many :submissions, :autosave => true
end

class Submission
  include Mongoid::Document
  belongs_to :account
end

a = Account.new
a.save!

s = Submission.new
s.update_attributes({"account" => {"id" => a.id}})
s.save!

a.id == s.account.id  # false

The call to update_attributes is creating a new blank Account object instead of referencing the existing one that I'm telling it to use. What's going on?

UPDATE

To be clear, I'm trying to process an HTML form in an update action which adds an Account to a Submission. I understand there are other ways to link these documents by writing specific code. But the normal rails way should allow me to use an HTML form to update the documents this way, right?

도움이 되었습니까?

해결책

Change your HTML form to make "account_id" not "account[id]" then it starts working:

s.update_attributes({"account_id" => a.id})
s.save!

a.id == s.account.id  # true
a == s.account # true

Very odd what it's doing. Maybe mongoid bug?

다른 팁

That's not the way to add s to a. What you want to do is this:

a = Account.new
a.submissions << Submission.new
a.save!
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top