Custom rails/mongoid relationship names not working

。_饼干妹妹 提交于 2019-12-11 23:08:56

问题


I'm trying to get custom relationship names to work in Mongo.

A "collage" is a BSON document filled with BSON fields that are Work Ids. Here's what's in the database for "collage":

Collage.create(slide_one: client.work.first.id, slide_two: client.work.second.id, slide_three: client.work.third.id)

So, a collage is mongo record full of work Ids. I'd like to be able to write @collage.work_one or @collage.slide_one.work_one, or @collage.slide_one.work to get to the Work I want.

Custom naming these associations is proving fruitless. So far I've tried two things:

This is how it seems to say to do it on the mongo website, but when I set it up and call @collage.work_one.inspect I get nil. http://mongoid.org/docs/relations.html (bottom of page)

collage.rb

has_one :work_one, class_name: 'Work', inverse_of: :slide_one

work.rb

belongs_to :slide_one, class_name: 'Collage', inverse_of: :work_one

@collage.work_one.inspect literally just prints out "nil"

.

.

I also tried

collage.rb

has_one :work_one, class_name: 'Work', as: :work_oneable

work.rb

belongs_to :work_oneable

But that gives me:

uninitialized constant WorkOneable

Any help or ideas much appreciated!


回答1:


I believe your class declaration is correct (the first one). However, you should use the actual objects instead of id when assigning the fields, like this:

Collage.create(slide_one: client.work.first, slide_two: client.work.second, slide_three: client.work.third)

Hope that helps.



来源:https://stackoverflow.com/questions/9201263/custom-rails-mongoid-relationship-names-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!